Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector on a string only works when surrounded by a div

Tags:

jquery

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

like image 422
Randall Sutton Avatar asked May 26 '09 17:05

Randall Sutton


People also ask

What does $() do in jQuery?

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.

What is wrapped set in jQuery?

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.

What does this jQuery selector do $( div p?

"$("div p")" Selects all elements matched by <div> that contain an element matched by <p>.

How do you get an HTML element from a string with jQuery?

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 .


1 Answers

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.

like image 86
Dmitri Farkov Avatar answered Nov 07 '22 05:11

Dmitri Farkov