jQuery selects elements different from my expectation!

Please open the Target Even Elements Using jQuery challenge. This challenge says to select the even targets and give them some classes. my answer was true (which was identical to hint solution) but when I try to select the elements in my mind according to the given selector (".target:even") I end up upon different nodes.

Here’s a minimal code please clear the code in the challenge and paste this:

<script>
  $(document).ready(function() {
    $(".target:even").addClass("animated shake");
  });
</script>

<div>
  <button class="target">child 0</button>
  <button class="target">child 1</button>
  <button class="target">child 2</button>
</div>

<div>
  <button class="target">child 0</button>
  <button class="target">child 1</button>
  <button class="target">child 2</button>
</div>

The tutorial says jQuery uses CSS selectors to select elements but it’s zero-indexed. The piece of code selecting element ( $(".target:even") ) , I can say it’s saying select all element with .target class which is even child. And because jQuery is zero-indexed, even means child 0 button and child 2 button in every div element. But if you run the code you see the selected elements are child 0 and child 2 buttons from first div but child 1 from the last div.

You have 6 target elements, so the :even selector selects the elements 0, 2 and 4. It doesn’t matter that they’re into separate divs, jQuery first gets the list of all .targets, then applies :even.

1 Like

Thank you. Is it because jQuery’s inner code excludes nth-child()?
If you use .target:nth-child(even) in basic CSS it behaves differently.

The CSS nth-child(even) selector and the jQuery element:even selector are different things. The CSS selector only works for elements that are all siblings (or n children ) in the same container, while the jQuery selector first grabs a whole list of elements (that can be located in different containers), and then sorts out the even-indexed ones.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.