tags:

views:

278

answers:

1

Why does this work?

$('#findme', '<div><div id="findme">Hello</div></div>')

And this does not?

$('#findme', '<div id="findme">Hello</div>')

For some reason only when I have the enclosing div will jQuery find the div with the id of findme.

Even enclosing it in a different tag does not work.

$('#findme', '<html><div id="findme">Hello</div></html>')

In addition the following don't work.

$('<div id="findme">Hello</div>').find('#findme')
$('<html><div id="findme">Hello</div></html>').find('#findme')

Although this works.

$('<div><div id="findme">Hello</div></div>').find('#findme')

There is something I'm not understanding about how the context works.

Thanks, Randall

+16  A: 

It is quite easy actually. The way you are searching is using context. So it takes the top-most node in the string, and searches through it's children.

So imagine having the same structure in html, and parsing it:

$('#findme', '<div><div id="findme"></div></div>')

is the same as

$('div').find('#findme')

OR

$('div').children('#findme')


So when you try

$('<div id="findme"></div>').find('#findme')

It obviously has no children.

Dmitri Farkov
+1 Really well explained ;)
Seb
I believe it's not ".findme" but "#findme" in your examples. Aside from that, well explained indeed
Pablo Fernandez
I find it odd the div with the enclosed html tag doesn't work either. Does this mean it is impossible to select a top level div in a string?
Randall Sutton
@Randall: if you know the string is only a div, doing $('<div id="findme">Hello</div>') is essentially creating the DIV you are looking for - you don't have to find it!
Paolo Bergantino
Not sure about the html tag, but I doubt thats often encountered.
Dmitri Farkov
@Randall: As the jQuery documentation notes: "Simple elements without attributes, e.g., "<div />", are created via document.createElement. All other cases are parsed by assigning the string to the .innerHTML property of a div element. The HTML string cannot contain elements that are invalid within a div, such as html, head, body, or title elements." http://docs.jquery.com/Core/jQuery#elements
Paolo Bergantino