Jerry
Jerry

Reputation: 2577

JQuery AJAX HTML Find Not Working

I've read similar Q/A on SO but this simple piece of JQuery AJAX code is still driving me nuts --

$.get($('#pager a').attr('href'), function(data) {
    var data = $(data).wrap("<div />");
    console.log(data);
    console.log(data.find('.content'));
    console.log(data.find('#next_page'));
}, "html");

The HTML returned by the AJAX call is --

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head></head>
  <body>
    <div class="content">lorum</div>
    <div class="content">ipsum</div>
    <div id="next_page">
      <a href="/page/2"></a>
    </div>
  </body>
</html>

And the console logs --

[<TextNode textContent="\n\n \n \n ">, div.content, <TextNode textContent="\n ">, div.content, <TextNode textContent="\n ">, div#next_page, <TextNode textContent="\n \n">]
[ ]
[ ]

I can't for my life figure out why data.find('.content') and data.find('#next_page') match nothing.

Any pointer will be greatly appreciated!

Upvotes: 2

Views: 1346

Answers (1)

Felix Kling
Felix Kling

Reputation: 816960

From the .wrap() [docs] documentation:

This method returns the original set of elements for chaining purposes.

The set of elements in this case are all the child nodes of body. .find() will search for descendants of these nodes, but not the nodes itself.

Either use .filter() [docs] instead or create an empty div and set data as its content:

var data = $('<div />').html(data);

Upvotes: 7

Related Questions