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.
- div.container is the wrapping element.
- div.photo, div.title and div.rating are immediate children of div.container.
- Each div.star is a child of div.rating.
- 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?
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for more daily web development tuts and articles.
Related Posts
Check out some more great tutorials and articles that you might like
Plus Members
Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.










User Comments
( ADD YOURS )Tanner September 9th
Nice post!
( )Adam September 9th
Thanks
( )Marcelo Kanzaki September 9th
very nice post!
( )Shuuun September 9th
Good to know for beginners! Very usefull when you cannt read docs (btw jquery docs are amazingly easy to read)
( )Matthew Booth September 9th
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?
( )Kenneth September 9th
Right on the page explaining the jQuery/$ core function: http://docs.jquery.com/Core/jQuery#expressioncontext
It’s known as context.
m3talsmith September 11th
@Matthew If your code is more complex than this then you are designing your structure wrong.
Daniel Sitnik September 9th
Nicely explained, thanks Park!
( )Chris M September 9th
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!
( )Wesley van Opdorp September 9th
Nice article, was looking for the selection of a certain element within $(this). Ended up using jQuery(”.ClassName”, this).
( )Kevin September 9th
i need this lesson!!! tHaNk YoU vErY mUcHhHhHhHh!!!
( )Ange Chierchia September 9th
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 September 9th
?
( )Colin September 9th
Excellent reference, thank you! I’m sure this will come in handy at some point.
( )crysfel September 9th
i always use this in my daily work
jQuery is an awesome framework, love it
( )IgnacioRV September 9th
There are a few I didn’t know (e.g. “parents”). I’ll come back here next time I work with jQuery.
( )Thanks!
Jonny September 9th
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 September 9th
Great tutorial, good work!
( )DominixZ September 9th
Very great article. You make my eyes open!.
( )Montana Flynn September 9th
Great tut! I Really like these jQuery tutorials that explain the basics. Thanks again nettuts!
( )Juan C Rois September 9th
Great info, many thanks. Keep up the good work.
( )Dean September 9th
Traversing the DOM is slower than static CSS selectors. Where possible minimise DOM traversing and manipulation – use CSS classes to define states.
( )James September 10th
huh?? I’d say the complete opposite is true.
( )Miles Johnson September 9th
Nice post but one thing bothers me. Say in example 2, why dont you just do:
$(’.rating .star.on’); ?
( )Nick Brown September 9th
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 September 9th
非常棒的文章!
( )Very nice tutorial!
franz September 10th
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”.
( )David Fitzgibbon September 10th
Very usefull, actually sorts out a problem I have at the moment!
( )LuK September 10th
Thanks for that walkthrough! Had problems with traversing multiple times =)
( )Johan September 10th
I cant think of any other widgets this would be useful for. Anyone?
( )Khalil September 10th
Awesome Work Thank you.
( )Vlad Dumitrica September 10th
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.
( )Dustin Lakin September 10th
Great article, I have found Jquery’s selectors very useful in my experiences.
( )Project Runway September 11th
Isnt this something like Peppy CSS3 selector engine?
( )Nikola Malich September 11th
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.
( )Daryn St. Pierre September 11th
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!
( )AtiKuSDesign September 11th
This is a great article for a very useful set of javascript functions.
Thanks very much!
( )tutorial blog September 12th
I very like all your site. I really attractive.
( )Nina September 14th
hey, a frienf of mine took that photo
( )zumbi September 14th
great article here and useful indeed. btw, where’s that photo with the clouds up there taken?
( )webangel78 September 15th
Lately I was thinking to start learn jQuery in depth and this tutorial is a great begining. Thanks!
( )Shahriar Hyder September 24th
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 October 21st
nice work
( )