Question

In the below code, why does $(data).find('#'); return null where as $(data).siblings('#'); does work properly?

$.get("post.php", function(data) {  

    var new_data = $(data).find('#main_wrapper').html();
    console.log(new_data); // returns NULL

    var new_data = $(data).siblings('#main_wrapper').html();
    console.log(new_data);  // returns all of the html inside #main_wrapper
                            // like you'd expect it to.  shown below.
                            // <div class="container" id="content"><div class="popup"><div class="latest"><h2>News</h2></div></div></div>

});

post.php is pasted in the pastebin here.

Was it helpful?

Solution

Let first note the main difference between siblings and find. Find search for descendant while sibling get same level nodes.

Knowing that should give you insight on what the problem is, right?

Well, .find will not find your element if has no parent while .siblings will not find any element that has parents.

ALSO, if there is only 1 element on the root of your data, sibling will return 0 element.

An infallible solution is to append your data to a fake DOM element like that :

$myWrapper = $('<div>').html(data).find('#main_wrapper');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top