Picture of Michael Lee
:wave: Hey hey, I'm Michael Lee and this is my site about being a developer, being a dad and making side projects.

jQuery .children() vs .find()

Written on June 8, 2016

Yesterday I was chaining jQuery’s .children() method to traverse to an element in the DOM but for reasons I couldn’t understand, the element wasn’t being selected.

Let’s say I had this snippet of HTML:

<div class='pizza-maker'>
  <ul class="toppings">
    <li class="topping pepporoni">
      <a href="#">Click to add more pepporoni to your pizza</a>
    </li>
    <li class="topping sausage">
      <a href="#">Click to add more sausage to your pizza</a>
    </li>
    <li class="topping cheese">
      <a href="#">Click to add more cheese to your pizza</a>
    </li>
  </ul>
</div>

Using jQuery’s .children() I was trying to target the anchor tag that allows me to add more cheese to my pizza. I thought I could chain .children() together like this:

$('.pizza-maker').children('.cheese').children('a').addClass('cheese-style')

Doing this, jQuery wouldn’t select the anchor tag, it actually didn’t select anything for me. I tried several other combinations of selectors hoping to get to the cheese anchor tag but it still didn’t work. It wasn’t until I stumbled across jQuery’s .find() method that I discovered the way .children() works is that it only traverses a single level down in the DOM tree.

The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

So using the example above, the first call to .children('.cheese') what was happening is, since this method was called on <div class='pizza-maker'></div> it looked for .cheese among the descendants immediately below it which is <ul class="toppings"></ul> and stopped there.

What I really should’ve used is the .find() method, which will continue to go through all the descendants of an element until it finds the selector you’re looking for. So the solution that actually worked the way I had intended was this:

$('.pizza-maker').find('.cheese').find('a').addClass('cheese-style')
Thanks for taking the time to read this article. I'd love to stay in touch and share more tips on programming and design and side projects. Sign up and I'll send you my articles straight to your email.