div") works differently than $ ("div"). Children ("div")? I have a weird problem where I cannot use a regular sizzle selector to selec...">

Why $ ("div> div") works differently than $ ("div"). Children ("div")?

I have a weird problem where I cannot use a regular sizzle selector to select something correctly in jQuery:

These two lines do not do the same.

ele.children("div.a > div").addClass("badActive"); ele.children("div.b").children("div").addClass("active"); 

http://jsfiddle.net/wGvEu/1/

+4
source share
2 answers

ele.children("div.a > div") selects div.a that are children of div.a elements (from the combinator > ) and ele (from the call to .children() ). It also means that ele itself represents a div.a element.

ele.children("div.b").children("div") selects div.b that are children of div.b , which themselves are children of ele . ele itself can be any element, but it must contain children div.b , and its children div.b must have children div .

As Felix Kling says in the comment above, you need to use .find() to search for all descendants. This applies to your first case with a combinator > , like ele.find("div.a > div") .

+7
source

Perhaps you want to:

ele.find("div.a > div").addClass("active");

This uses only one sizzle selector and achieves what you want. BoltClock is right why your two examples do not work the same. Another way of saying: .children() gets only direct children, while .find() gets something in the hierarchy under the "current" element.

+1
source

All Articles