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?


Tags: jQuery
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Tanner

    Nice post!

  • http://www.adam-mz.pl Adam

    Thanks :)

  • Marcelo Kanzaki

    very nice post!

  • Shuuun

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

    • http://www.aftertheone.com Matthew Booth

      They are easy to read because they are very basic. Most of the docs involving filtering or traversing actually explain very little about real world ways of applying the information. Read Wesley van Opdorp’s comment below, where is that method of filtering in the docs?

  • http://www.encoder2002.com Daniel Sitnik

    Nicely explained, thanks Park!

  • Chris M

    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!

  • http://www.yonego.nl/ Wesley van Opdorp

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

  • Kevin

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

  • http://angechierchia.com Ange Chierchia

    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

    • efe

      ?

  • http://www.colingreig.com Colin

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

  • http://www.quizzpot.com crysfel

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

  • IgnacioRV

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

  • Jonny

    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

  • Mosselman

    Great tutorial, good work!

  • http://www.dominixz.com DominixZ

    Very great article. You make my eyes open!.

  • http://complimedia.com Montana Flynn

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

  • http://www.fatlizardmedia.com Juan C Rois

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

  • Dean

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

    • http://james.padolsey.com James

      huh?? I’d say the complete opposite is true.

  • http://milesj.me/ Miles Johnson

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

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

  • http://www.nickbrowndesign.com/ Nick Brown

    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

  • Alex Lau

    非常棒的文章!
    Very nice tutorial!

  • franz

    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”.

  • http://davidfitzgibbon.com David Fitzgibbon

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

  • LuK

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

  • http://www.johandesilva.co.uk Johan

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

  • Khalil

    Awesome Work Thank you.

  • http://reakt.mobi/ Vlad Dumitrica

    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.

  • http://dustinlakin.com Dustin Lakin

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

  • http://www.webdesignexpert.me Project Runway

    Isnt this something like Peppy CSS3 selector engine?

  • Nikola Malich

    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.

  • http://www.bloqhead.com Daryn St. Pierre

    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!

  • http://www.d-lists.co.uk AtiKuSDesign

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

    Thanks very much!

  • http://tutorialblog.info/ tutorial blog

    I very like all your site. I really attractive.

    • angry

      its not a show to show u!

  • Nina

    hey, a frienf of mine took that photo :D

  • zumbi

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

  • http://www.webangel78.com webangel78

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

  • http://technosiastic.wordpress.com Shahriar Hyder

    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/

  • Sachin

    nice work

  • chinijo

    Muy Bueno Gracias

  • Gordon

    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

  • sandeep

    its not a solution

  • Mateus

    jquery selectors are so powerfull.

  • http://www.denisdeng.com denisdeng

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

  • http://webpositie.livejournal.com/ Alfonso Roelfstra

    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.

  • Joginder

    Thanks, A Great Post

  • Pappie

    Great … Thanks Lot ….