A few days ago I was working on a project where I needed to set the "active" state of <li> elements across multiple containers. These containers were divided into separate tabs, so one could be viewed at a time, but when one container updated, all the others needed to be updated as well.

Check out the instructions and code after the jump!

So, basically, what we're doing is:

  • Select all parent containers with the class of "parent", and for each container we "find" all elements with the class "asd".
  • Note that all 4 of the parent contains have elements with the same class. This is where the power of jQuery selectors comes into the picture.
  • Using $(e.target).index(), we retrieve the "index" of the link that was just clicked. This lets us store the position of the element we clicked.
  • Then, we perform some "recursion" and re-select each parent container.
  • Inside of each re-selected parent element, we use the previously stored position of what we clicked, to select the proper child element.
  • RESULT: If you click item 2, it will select the 2nd item inside every single parent container.
If you have any questions, feel free to ask in the comments below!