2

I'm using the following javascript function to load content from another url to the current document. Why are contentHtml and menuHtml undefined, what did I wrong? I also don't know what the [prevObject.. means, does this look ok or is there already something wrong?

    function exhibitload(url) {
        $.get(url, {}, function (data) {
            console.log(data);
            var content = $(data).find('#exhibit');
            var menu = $(data).find('#index');

            console.log(content); // [prevObject: n.fn.init[47], context: undefined, selector: "#exhibit", jquery: "2.1.3", constructor: function…]
            console.log(menu); // [prevObject: n.fn.init[47], context: undefined, selector: "#index", jquery: "2.1.3", constructor: function…]

            var contentHtml = $(content).html();
            var menuHtml = $(menu).html();

            console.log(contentHtml); // undefined
            console.log(menuHtml);  // undefined

            $('#exhibit').html(contentHtml);
            $('#index').html(menuHtml);
            $('body').removeClass('loading');
        });
    }
4
  • 1
    works fine here jsfiddle.net/28abyns7 Commented Feb 19, 2015 at 14:38
  • 1
    can u show the data that u get from the url? Commented Feb 19, 2015 at 14:45
  • @NaeemShaikh , no, it doesn't work - jsfiddle.net/28abyns7/2 Commented Feb 19, 2015 at 15:03
  • Use .filter() instead of find(). Commented Feb 19, 2015 at 15:23

2 Answers 2

3

You're trying to .find() the element within the element (jQuery objects set containing the element) itself. You have to search for the element in one of its parents, which is a separate jQuery object (<div> in the example below)

Try this one:

var html = $('<div/>').append(data);
var content = html.find('#exhibit');
var menu = html.find('#index');

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

Change find():

        var content = $(data).find('#exhibit');
        var menu = $(data).find('#index');

To filter():

        var content = $(data).filter('#exhibit');
        var menu = $(data).filter('#index');

DEMO

var data = $('body').contents();
console.log( data );
var exh = $(data).filter('#exhibit');
console.log( 'Exhibit' );
console.log( exh[0] );
var ind = $(data).filter('#index');
console.log( 'Index' );
console.log( ind[0] );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Here's all the data:
<div id="exhibit">Exhibit Div</div>
<div id="index">Index Div</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.