4

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/

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Incognito
  • 20,537
  • 15
  • 80
  • 120
  • 4
    `children`, as the name says, only searches the *children* of an element. If you want to search all *descendants*, you have to use `find`. What you probably want is: `ele.find("> div.a > div")`. – Felix Kling Jul 14 '11 at 18:42
  • 1
    You have to think differently. `children` selects every child and tests whether it matches this selector. In order for a child to match, it must be a `div` and have `div.a` as parent. I think it is better to think about these methods as *filtering* methods. `children` selects *all children*, `find` *all descendants* and then only those elements are kept that can satisfy the condition (the selector). – Felix Kling Jul 14 '11 at 18:45

2 Answers2

7

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").

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

Probably what you want is:

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

That uses the just a single sizzle selector and achieves what you want. BoltClock is right about why your two examples don't work the same. Another way to say it is: .children() only gets the direct children, whereas .find() will get anything in the hierarchy below the "current" element.

Jeff Gran
  • 1,585
  • 15
  • 17