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
When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.
The wrapped set is simply a list of DOM elements(with their children) in the order in which they are defined in the current document that matches a selector or in the order in which they have been created on the fly with the $(html) function.
"$("div p")" Selects all elements matched by <div> that contain an element matched by <p>.
Yes, you can use $. find —but only if you want just elements inside the outermost element, the div' in this example. The find` method only matches descendants. You could not find the div in this example--but, you can filter the div because the filter method matches any/all elements, including the outermost div .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With