Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is $("div > div") working differently than $("div").children("div")?

I have a weird problem where I can't use the normal sizzle selector to correctly select something in jQuery:

These two lines don't do the same thing.

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

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

like image 235
Incognito Avatar asked Feb 23 '23 14:02

Incognito


1 Answers

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

ele.children("div.b").children("div") selects divs that are children of div.b elements, that themselves are children of ele. ele itself may be any kind of element, but it must contain div.b children, and its div.b children need to have div children.

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

like image 78
BoltClock Avatar answered Mar 08 '23 12:03

BoltClock