Luca Steeb
Luca Steeb

Reputation: 1849

jQuery .html() from object returns undefined

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');
        });
    }

Upvotes: 2

Views: 4348

Answers (2)

PeterKA
PeterKA

Reputation: 24638

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>

Upvotes: 0

Artur Filipiak
Artur Filipiak

Reputation: 9157

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

Upvotes: 3

Related Questions