preview

10 Really Helpful Traversing Functions in jQuery

With jQuery, selecting HTML elements is laughably easy. But at times, we may wish to further refine the selection, which can be a hassle when the HTML structure is complicated. In this tutorial, we’ll explore ten ways that we can refine and extend a set of wrapped elements that we wish to operate upon.

The HTML

First of all, let’s take a look at the simple webpage shown in the figure below. We’ll be selecting elements in it throughout this tutorial.

  1. div.container is the wrapping element.
  2. div.photo, div.title and div.rating are immediate children of div.container.
  3. Each div.star is a child of div.rating.
  4. When a div.star has the ‘on’ class, it’s a full star.

Why Traversing?

But why do we need to further refine a set of elements? Isn’t jQuery’s selection syntax powerful enough?

Well, let’s see an example. In the webpage mentioned above, when a star is clicked on, we may wish to add the ‘on’ class to this very star and every single star to the left of it. And we may want to change the background color of the parent div of the stars. So we have the following code.

$('.star').click(function(){
	$(this).addClass('on');
//	How to select the parent div of 'this'?
//	How to select stars to the left side of 'this'?
});

In Line 2, we select the very star that gets clicked on with ‘this‘. But how do we select the parent div of the stars? Yes, it’s div.rating. But there can be a dozen other div.ratings in a page, right? So which is the one we want? And how do we select all stars to the left of ‘this‘?

Fortunately, jQuery allows us to get new wrapped sets from an existing set, based on the hierarchical relationships. And this is in part what traversing functions do.

1. children

This function gets the immediate children of a set of elements.

This can be very handy in a variety of situations. Look at the figure below:

  • The container of the stars are selected initially.
  • A selector expression is passed to children() to narrow the result down to only the full stars.
  • If children() receives no parameters, all immediate children will be returned.
  • No grandchildren will be returned. Sorry.

2. filter

This function filters out elements from the wrapped set using a passed selector expression. Any elements that doesn’t match the expression will be removed from the selection.

The following example should be pretty straightforward. The full stars are filtered out from a collection of all five stars.

3. not

Quite the opposite from filter(), not() removes the matching elements from the wrapped set.

See the example below. Even stars are removed from the selection, leaving only the odd ones.

Notice! “Even” and “odd” selectors are zero-indexed. They count index from 0, NOT 1.

4. add

What if we want to add some elements to the wrapped set? The add() function does this.

Again, very straightforward. The photo box is added to the selection.

5. slice

Sometimes we may wish to obtain a subset of the wrapped set, based on the position of elements within the set. And slice() is the way to go.

  • The first parameter is the zero-based position of the first element to be included in the returned slice.
  • The second parameter is the zero-based index of the first element NOT to be included in the returned slice. If omitted, the slice extends to the end of the set.
  • So slice(0, 2) selects the first two stars.

6. parent

The parent() function selects the direct parent of a set of elements.

As shown in the figure below, the first star’s direct parent is selected. Very handy, hah? It should be noted that only the direct parent will be returned, which is why it’s singular. No grandparent or ancestors will be selected.

7. parents

This one is plural! The parents() function selects all ancestors of a set of elements. I mean ALL ancestors from the direct parent all the way up to ‘body‘ and ‘html‘. So it’s best to pass a selector expression to narrow down the result.

By passing ‘.container‘ to parents(), div.container, which actually is the grandparent of the first star, is selected.

8. siblings

This function selects all siblings (brothers and sisters) of a set of elements. An expression can be passed to filter the result.

Look at the example:

  • Who’s the first star’s siblings? The other four stars, right?
  • The ‘odd’ siblings are selected as shown. Again, the index is zero-based. Look at the red numbers below the stars.

9. prev & prevAll

The prev() function selects the previous (one) sibling, and prevAll() selects all previous siblings of a set of elements.

This is super handy if you’re building a star rating widget. The previous siblings of the third star are selected.

10. next & nextAll

These functions work in the same way as prev and prevAll, except for that they select the NEXT siblings.

Conclusion

At last, let’s see how these functions solve a real world headache for us.

$('.star').click(function(){
	$(this).addClass('on');

//	How to select the parent div of 'this'?
	$(this).parent().addClass('rated');

//	How to select stars to the left side of 'this'?
	$(this).prevAll().addClass('on');
	$(this).nextAll().removeClass('on');
});

This is the very problem we mentioned early in this tutorial, right? Several traversing functions are used in these lines of code.

  • In Line 5, look at the use of parent(). Easy, hah?
  • In Line 8 and 9, prevAll() and nextAll() select the to-be full stars and empty stars.

Now, we have an idea how handy traversing functions can be. They can be even more powerful when used together. The output of one function can be the input of another – that is to say, they’re chainable.

Thanks for reading! Hopefully this tutorial makes your life a bit easier when selecting HTML elements with jQuery. Any thoughts? Which traversing functions did we miss?


Add Comment

Discussion 51 Comments

  1. Tanner says:

    Nice post!

  2. Marcelo Kanzaki says:

    very nice post!

  3. Shuuun says:

    Good to know for beginners! Very usefull when you cannt read docs (btw jquery docs are amazingly easy to read)

  4. Nicely explained, thanks Park!

  5. Chris M says:

    How useful is it to post all the code snippets in images???

    Besides that, I love jQuery and I’m always glad to see another post related to it!

  6. Nice article, was looking for the selection of a certain element within $(this). Ended up using jQuery(“.ClassName”, this).

  7. Kevin says:

    i need this lesson!!! tHaNk YoU vErY mUcHhHhHhHh!!!

  8. Hi,

    Nice tut! I’m new to jQuery and I must say that this demonstrations are very interesting.

    I had to do a star rating system for one of my projects but didn’t know this functions, so I used a listbox for change the rating… too bad.

    thanks for sharing

  9. Colin says:

    Excellent reference, thank you! I’m sure this will come in handy at some point.

  10. crysfel says:

    i always use this in my daily work :D jQuery is an awesome framework, love it :D

  11. IgnacioRV says:

    There are a few I didn’t know (e.g. “parents”). I’ll come back here next time I work with jQuery.
    Thanks!

  12. Jonny says:

    Great! Jquery is (in my humble opinion) one of the absolute best tools available to any modern web or UI designer.

    My favorite two are slice and eq(index):

    $(‘.star’).eq(2); // SELECTS the 3rd star

  13. Mosselman says:

    Great tutorial, good work!

  14. DominixZ says:

    Very great article. You make my eyes open!.

  15. Great tut! I Really like these jQuery tutorials that explain the basics. Thanks again nettuts!

  16. Juan C Rois says:

    Great info, many thanks. Keep up the good work.

  17. Dean says:

    Traversing the DOM is slower than static CSS selectors. Where possible minimise DOM traversing and manipulation – use CSS classes to define states.

  18. Nice post but one thing bothers me. Say in example 2, why dont you just do:

    $(‘.rating .star.on’); ?

  19. Nick Brown says:

    Great post. Selection is definitely the heart of jQuery. On a similar note, there are two great posts on the same subject over at learningjquery.com

    http://www.learningjquery.com/2006/11/how-to-get-anything-you-want-part-1

    http://www.learningjquery.com/2006/12/how-to-get-anything-you-want-part-2

  20. Alex Lau says:

    非常棒的文章!
    Very nice tutorial!

  21. franz says:

    nice writeup, although it neglects the maybe most important fact: readabiliy of code. when using “cryptical” selectors like

    $(‘.rating n-th-child(3)’).prevAll()

    on a larger basis you end up with perlish, semi-obfuscated javascript code – a maintenance and documentation nightmare.

    I prefer selector methods like .children(), .find() instead of “css selectors on steroids”.

  22. Very usefull, actually sorts out a problem I have at the moment!

  23. LuK says:

    Thanks for that walkthrough! Had problems with traversing multiple times =)

  24. Johan says:

    I cant think of any other widgets this would be useful for. Anyone?

  25. Khalil says:

    Awesome Work Thank you.

  26. I played with it a bit and by chaining I ended up with this:

    $('.star').click(function(){
    $(this).parent().addClass('rated').end().prevAll().andSelf().addClass('on').end().end().nextAll().removeClass('on');
    });

    BTW, you should also post the source so that people who want to play shouldn’t code from scratch.

  27. Dustin Lakin says:

    Great article, I have found Jquery’s selectors very useful in my experiences.

  28. Isnt this something like Peppy CSS3 selector engine?

  29. Nikola Malich says:

    Thanks for the great post Park. I honestly never really looked at the silice() method before reading this. It is so useful and much easier to use / cleaner than combining the :gt and :lt selectors.

  30. This is awesome and easily explained. I’m going to use this endlessly. I had a project recently where I desperately needed a way to traverse easier. This would’ve been a huge help. Thanks!

  31. AtiKuSDesign says:

    This is a great article for a very useful set of javascript functions.

    Thanks very much!

  32. I very like all your site. I really attractive.

  33. Nina says:

    hey, a frienf of mine took that photo :D

  34. zumbi says:

    great article here and useful indeed. btw, where’s that photo with the clouds up there taken?

  35. webangel78 says:

    Lately I was thinking to start learn jQuery in depth and this tutorial is a great begining. Thanks!

  36. Very helpful traversing functions for jQuery indeed mate. I have also linked to yours from my blog post below where I am trying to collect the most useful and common jQuery code snippets for JavaScript over the web. Here is the title and the link to the jQuery link compilation endeavor:

    Ultimate collection of top jQuery tutorials, tips-tricks and techniques to improve performance

    http://technosiastic.wordpress.com/2009/09/24/collection-of-top-jquery-tutorials-tips-tricks-techniques-to-improve-performance/

  37. Sachin says:

    nice work

  38. chinijo says:

    Muy Bueno Gracias

  39. Gordon says:

    GREAT basic transversing. Anyone have more info using brackets?

    I’m wrestling w/ radio buttons…

    $(“input[name='radio_name']:checked”).val();
    $(“input[name^='rad']:checked”).val();//element name starts with “rad”
    $(“input[name*='radio_name']:checked”).val();//also filtering but I don’t know

  40. sandeep says:

    its not a solution

  41. Mateus says:

    jquery selectors are so powerfull.

  42. denisdeng says:

    very helpful,I have translate into Chinese—http://www.denisdeng.com/?p=695

  43. I simply needed to thank you very much again. I am not sure the things that I might have tried in the absence of the entire secrets revealed by you regarding such a theme. It truly was a alarming concern in my view, but discovering the expert style you handled the issue made me to leap for contentment. I will be happy for the assistance and as well , sincerely hope you recognize what an amazing job that you’re accomplishing instructing people today all through a web site. I am sure you’ve never got to know all of us.

  44. Joginder says:

    Thanks, A Great Post

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.