HTML converted to jQuery collection not searchable with selectors?

Posted by jimp on Stack Overflow See other posts from Stack Overflow or by jimp
Published on 2012-09-26T21:29:30Z Indexed on 2012/09/26 21:37 UTC
Read the original article Hit count: 269

Filed under:
|

I am trying to dynamically load a page using $.get(), parse the return with var $content = $(data), and ultimately use selectors to find only certain parts of the document. Only I cannot figure out why the jQuery collection returned from $(data) does not find some very basic selectors.

I set up a jsFiddle to illustrate the problem using a very small string of HTML.

<html>
<head>
<title>See Our Events</title>
</head>
<body><div id="content">testing</div></body>
</html>

I want to find the <title> node.

var html = "<html>\n"+
"<head>\n"+
"  <title>See Our Events</title>\n"+
"</head>\n"+
"<body><div id=\"content\">testing</div></body>\n"+
"</html>";
var $content = $(html);
console.log($content.find('title').length); // Logs 0. Why?

If I wrap a <div> around the HTML, then the selector works. (But if you look at the jsFiddle, other variations of the selector still do not work!)

var html = "<div><html>\n"+
"<head>\n"+
"  <title>See Our Events</title>\n"+
"</head>\n"+
"<body><div id=\"content\">testing</div></body>\n"+
"</html></div>";
var $content = $(html);
console.log($content.find('title').length); // Logs 1.

Please look at the jsFiddle, too. It contains more examples than my code here to keep the post easier to read.

Why does my otherwise very basic selector not return the title node?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about jquery-selectors