If I run this code –
var html= '<html><head></head><body><div class="bar"></div></body></html>';
console.log($(html).find('div'));
I get no results returned, if I run this code –
var html= '<html><head></head><body><div><div class="bar"></div></div></body></html>';
console.log($(html).find('div'));
Then I get a single result returned – the inner div (<div class="bar"></div>). I would have expected the first code snippet to return a single result and the second snippet two results.
Similarly, this code returns no results –
var code = $("<div id='foo'>1</div><div id='bar'>2</div>");
console.log(code.find('div'));
but this code alerts ‘div’ twice –
var code = $("<div id='foo'>1</div><div id='bar'>2</div>");
code.each(function() {
alert( this.nodeName );
})
Given the result of the second snippet, I would have expected the first code snippet to return two results. Could someone please explain why I’m getting the results I’m getting?
Let’s split this question into two parts.
First:
and
do not work because according to the
jQuery()docs:<html>,<head>, and<body>tags are getting stripped out, and<div class="bar"></div>remains.findonly searches inside the resulting<div>, and cannot find anything.<html>,<head>, and<body>tags are getting stripped out, and<div><div class="bar"></div></div>remains.findsearches inside the result, and finds a single<div>.As for your second part:
You first give jQuery a string, which it takes and makes into a jQuery object with the two
<div>‘s. Then,findsearches in each<div>, finds nothing and returns no results.Next, in
eachloops through the jQuery object, taking each of the two created<div>‘s, and alerts their node name. Therefore, you get two alerts.