Tree TraversalS2C Home « Tree Traversal

If you have worked with JavaScript for a while, you will know the amount of effort involved in traversing the DOM tree to get to elements we need to interact with. The coding can become quite long winded and complex, so wouldn't it be nice if we had an easier way to do this? jQuery to the rescue!

jQuery has traversal methods that allow us to find parents, children and siblings elements within the DOM tree. The library also has methods to walk further up or down the DOM tree to find other ancestors and descendant elements.

In this lesson we take our first look at how jQuery simplifies navigation through the DOM by looking at the methods available for navigating the DOM hierarchy.

Tree Traversal Methods Description
Traversing Up The Dom Tree
.closest()Retrieve the first element matching the specified selector, element or jQuery object, starting with the current element and progressing up through the DOM tree.
.offsetParent()Retrieve the closest positioned ancestor element.
.parent()Retrieve the parent of each element within the matched set.
.parents()Retrieve the ancestors of each element within the matched set.
.parentsUntil()Retrieve the ancestors of each element within the matched set, up to but not including the selector, DOM node, or jQuery object specified.
Traversing Down The Dom Tree
.children()retrieve the children of each element within the matched set.
.find()Retrieve the descendants of each element in the current matched set, filtered by a specified selector, element or jQuery object.
Traversing The Same Level Of The Dom Tree
.next()Retrieve the immediately following sibling of each element within the matched set.
.nextAll()Retrieve all following siblings of each element within the matched set.
.nextUntil()Retrieve all following siblings of each element within the matched set, up to but not including the selector, DOM node, or jQuery object specified.
.prev()Retrieve the immediately preceding sibling of each element within the matched set.
.prevAll()Retrieve all preceding siblings of each element within the matched set.
.prevUntil()Retrieve all preceding siblings of each element within the matched set, up to but not including the selector, DOM node, or jQuery object specified.
.siblings()Retrieve the siblings of each element within the matched set.

Traversing Up The Dom Tree

In this section we look at the jQuery methods available for traversing up through the DOM tree.

The .closest() Method  Top

Retrieve the first element matching the specified selector, element or jQuery object, starting with the current element and progressing up through the DOM tree.

We will be using the .closest( selector [, context ] ) signature for our example which retrieves the first element matching the specified selector, starting with the current element and progressing up through the DOM tree optionally filtered by a context..

There are two other signatures available for the .closest() method, .closest( element ) and .closest( jQuery object ) which are covered in the reference section.

Ok lets go though each button press in the example below and see what we are doing:

When the left button is pressed we select the closest 'li' element to the list item marked with a class of 'list1' which is in fact itself and then change the background colour to olive.

When the middle button is pressed we select the closest 'ol' element to the list item marked with a class of 'list2' then change the background colour to orange.

When the right button is pressed we select the closest 'ol' element to the list item marked with a class of 'list3' and then change the background colour to teal. In this example we are using a DOM context to look up the DOM tree within.

  1. Things To Do When I Get Up  (id of list1)
    1. Put The Kettle On
    2. Put The Teabag in The Cup
    3. Wait for Kettle To Boil
    4. Pour Boiling Water In The Cup  (id of list2)
      1. Wait for tea to brew
      2. Remove teabag
        1. Pour in milk  (id of list3)
        2. Stir tea
  2. Things To Do When I Go To Bed


$(function(){
  $('#btn1').on('click', function() {
    $('#list1').closest('li')
               .css('backgroundColor', 'olive');
  });
  $('#btn2').on('click', function() {
    $('#list2').closest('ol')
               .css('backgroundColor', 'orange');
  });
  $('#btn3').on('click', function() {
    var list2 = document.getElementById('list2');
    $('#list3').closest('ol', list2)
               .css('backgroundColor', 'teal');
  });
});

Press the button below to action the above code:

            


The .offsetParent() Method  Top

Retrieve the closest positioned ancestor element.

In the example below we use the .offsetParent() method to find the closest positioned ancestor element of the list item with an id of 'list4'. The list item below marked with (position relative) and turn the background colour to yellow.

  1. Things To Do When I Get Up  (id of list1)
    1. Put The Kettle On
    2. Put The Teabag in The Cup
    3. Wait for Kettle To Boil
    4. Pour Boiling Water In The Cup (position relative)
      1. Wait for tea to brew
      2. Remove teabag
        1. Pour in milk
        2. Stir tea  (id of list4)
  2. Things To Do When I Go To Bed


$(function(){
  $('#btn4').on('click', function() {
    $('#list4').offsetParent()
               .css('backgroundColor', 'yellow');
  });
});

Press the button below to action the above code:


The .parent() Method  Top

Retrieve the parent of each element within the matched set.

We will be using the .parent( selector ) signature for our example which will retrieve the parent of each element within the matched set that matches the specified selector.

The other signature available .parent() is parameterless and will retrieve the parent of each element within the matched set and is covered in the reference section.

In the example below we select only 'span' parents of each 'a' element within the #main section of the page and turn the background colour to orange.


$(function(){
  $('#btn5').on('click', function() {
    $('#main a').parent('span')
                .css('backgroundColor', 'orange');
  });
});

Press the button below to action the above code:


The .parents() Method  Top

Retrieve the ancestors of each element within the matched set.

This method has two signatures available .parents() which is parameterless and will retrieve the ancestors of each element within the matched set.

The second signature .parents( selector ) will retrieve the ancestors of each element within the matched set that matches the specified selector.

Examples of both signatures are available in the reference section.

The .parentsUntil() Method  Top

Retrieve the ancestors of each element within the matched set, up to but not including the selector, DOM node, or jQuery object specified.

The .parentsUntil() method is very similar to the .parents() method but gives us more control by allowing us to stop at a certain ancestor with additional filtering by another selector.

This method has four signatures available .parentsUntil() which is parameterless and will retrieve the ancestors of each element within the matched set exactly the same way as the .parents() method.

The second signature parentsUntil( selector [, filter ] ) will retrieve the ancestors of each element within the matched set, stopping at the specified selector, optionally filtered by another selector.

The third signature parentsUntil( element [, filter ] ) will retrieve the ancestors of each element within the matched set, stopping at the specified DOM node, optionally filtered by another selector.

The fourth signature parentsUntil( jQuery object [, filter ] ) will retrieve the ancestors of each element within the matched set, stopping at the specified jQuery object, optionally filtered by another selector.

Examples of all four signatures are available in the reference section.

Traversing Down The Dom Tree

In this section we look at the jQuery methods available for traversing down through the DOM tree.

The .children() Method  Top

Retrieve the children of each element within the matched set.

We will be using the .children() signature which is parameterless and will retrieve the children of each element within the matched set.

The other signature children( selector ) will retrieve the ancestors of each element within the matched set that match the specified selector.

Examples of this signature is available in the reference section.

In the example below we select all children of 'h2' elements within the #main section of the page and turn the background colour of their children yellow.


$(function(){
  $('#btn6').on('click', function() {
    $('#main h3').children()
                 .css('backgroundColor', 'yellow');
  });
});

Press the button below to action the above code:


The .find() Method  Top

Retrieve the descendants of each element in the current matched set, filtered by a specified selector, element or jQuery object.

We will be using the .find( jQuery object ) signature for our example, which retrieves the parent of each element within the matched set that matches the specified jQuery object.

The second signature .find( selector ) will retrieve the descendants of each element within the matched set that matches the specified selector.

The third signature .find( element ) will retrieve the descendants of each element within the matched set that matches the specified element.

Examples of these signatures are available in the reference section.

In the example below we create a jQuery object containing elements with a class of 'list3'. We then do a find on this jQuery object from the li item with an id of 'list1b'.

  1. Things To Do When I Get Up
    1. Put The Kettle On
    2. Put The Teabag in The Cup
    3. Wait for Kettle To Boil
    4. Pour Boiling Water In The Cup
      1. Wait for tea to brew  (class of list3)
        1. tea brewed
      2. Remove teabag
      3. Pour in milk  (class of list3)
        1. Stir tea
  2. Things To Do When I Go To Bed


$(function(){
  $('#btn7').on('click', function() {
    var $listitem = $('li .list3');
    $('li #list1b').find( $listitem )
                   .css('backgroundColor', 'orange');
  });
});

Press the button below to action the above code:


Traversing The Same Level Of The Dom Tree

In this section we look at the jQuery methods available for use with siblings.

The .next() Method  Top

Retrieve the immediately following sibling of each element within the matched set.

This method has two signatures available, the .next() which is parameterless and will retrieve the immediately following sibling of each element within the matched set.

The second signature .next( selector ) will retrieve the immediately following sibling of each element within the matched set, but only if it matches the specified selector.

Examples of both signatures are available in the reference section.

The .nextAll() Method  Top

Retrieve all following siblings of each element within the matched set.

We will be using the .nextAll() signature for our example, which is parameterless and will retrieve all following siblings of each element within the matched set.

The other signature .next( selector ) will retrieve all following siblings of each element within the matched set, but only if it matches the specified selector.

Examples of these signatures are available in the reference section.

In the example below we select all following 'tr' elements within the table that come after the 'tr' element with the id of 'trid1 and then change the background colour within the matched set.

Table For Testing The .nextAll() Method
Table Row 1, Table Data 1 Table Row 1, Table Data 2
Table Row 2 (id of trid1), Table Data 1 Table Row 2 (id of trid1), Table Data 2
Table Row 3, Table Data 1 Table Row 3, Table Data 2
Table Row 4, Table Data 1 Table Row 4, Table Data 2


$(function(){
  $('#btn8').on('click', function() {
    $('.testtable #trid1').nextAll()
                          .css('backgroundColor', 'orange');
  });
});

Press the button below to action the above code:


The .nextUntil() Method  Top

Retrieve all following siblings of each element within the matched set, up to but not including the selector, DOM node, or jQuery object specified.

This method has four signatures available .nextUntil() which is parameterless and will retrieve the following siblings of each element within the matched set exactly the same way as the .nextAll() method.

The second signature nextUntil( selector [, filter ] ) will retrieve the following siblings of each element within the matched set, stopping at the specified selector, optionally filtered by another selector.

The third signature nextUntil( element [, filter ] ) will retrieve the following siblings of each element within the matched set, stopping at the specified DOM node, optionally filtered by another selector.

The fourth signature nextUntil( jQuery object [, filter ] ) will retrieve the following siblings of each element within the matched set, stopping at the specified jQuery object, optionally filtered by another selector.

Examples of all four signatures are available in the reference section.

The .prev() Method  Top

Retrieve the immediately preceding sibling of each element within the matched set.

This method has two signatures available, the .prev() which is parameterless and will retrieve the immediately preceding sibling of each element within the matched set.

The second signature .prev( selector ) will retrieve the immediately preceding sibling of each element within the matched set, but only if it matches the specified selector.

Examples of both signatures are available in the reference section.

The .prevAll() Method  Top

Retrieve all preceding siblings of each element within the matched set.

This method has two signatures available, the .prevAll() signature, which is parameterless and will retrieve all preceding siblings of each element within the matched set.

The other signature .prevAll( selector ) will retrieve all preceding siblings of each element within the matched set, but only if it matches the specified selector.

Examples of both signatures are available in the reference section.

The .prevUntil() Method  Top

Retrieve all preceding siblings of each element within the matched set, up to but not including the selector, DOM node, or jQuery object specified.

We will be using the prevUntil( element [, filter ] ) signature for our example, which will retrieve the preceding siblings of each element within the matched set, stopping at the specified DOM node, optionally filtered by another selector.

The second signature .prevUntil() which is parameterless and will retrieve the preceding siblings of each element within the matched set exactly the same way as the .prevAll() method.

The third signature prevUntil( selector [, filter ] ) will retrieve the preceding siblings of each element within the matched set, stopping at the specified selector, optionally filtered by another selector.

The fourth signature prevUntil( jQuery object [, filter ] ) will retrieve the preceding siblings of each element within the matched set, stopping at the specified jQuery object, optionally filtered by another selector.

Examples of all four signatures are available in the reference section.

In the example when the left button is pressed below we select all preceding 'tr' elements within the table that come before the 'tr' element with the id of 'trid2. We then select all siblings we find until we hit the DOM node we saved from the DOM element with the id of 'trid3'. We then change the background colour within the matched set.

In the example when the right button is pressed below we select all preceding 'tr' elements within the table that come before the 'tr' element with the id of 'trid2, filtered with a class of 'trclass1'. We then select all siblings we find until we hit the DOM node we saved from the DOM element with the id of 'trid3'. We then change the background colour within the matched set.

Table For Testing The .prevUntil( element [, filter] ) Method
Heading 1 Description 1
Table Row 1 (id of trid3), Table Data 1 Table Row 1 (id of trid3), Table Data 2
Table Row 2, Table Data 1 Table Row 2, Table Data 2
Heading 2 Description 2
Table Row 3 (class of trclass1), Table Data 1 Table Row 3 (class of trclass1), Table Data 2
Table Row 4, Table Data 1 Table Row 4, Table Data 2
Heading 3 Description 3
Table Row 5 (class of trclass1), Table Data 1 Table Row 5 (class of trclass1), Table Data 2
Table Row 6 (id of trid2), Table Data 1 Table Row 6 (id of trid2), Table Data 2


$(function(){
  $('#btn9').on('click', function() {
    var trid3 = document.getElementById("trid3");
    $('.testtable2 #trid2').prevUntil(trid3)
                           .css('backgroundColor', 'green');
  });
  $('#btn10').on('click', function() {
    var trid3 = document.getElementById("trid3");
    $('.testtable2 #trid2').prevUntil(trid3, '.trclass1')
                           .css('backgroundColor', 'red');
  });
});

Press the button below to action the above code:

            


The .siblings() Method  Top

Retrieve the siblings of each element within the matched set.

We will be using the .siblings( selector ) signature for our example, which will retrieve the siblings of each element within the matched set, but only if they match the specified selector.

The other signature .siblings() which is parameterless and will retrieve the siblings of each element within the matched set.

Examples of these signatures are available in the reference section.

In the example below we select all siblings of the 'tr' elements with an id of '#trid2', filtered by a class of 'trclass1' and turn the background colour of siblings to teal. Notice how the element used to find our siblings is not included in the match.

Table For Testing The .siblings( selector ) Method
Table Row 1 (class of trclass2), Table Data 1 Table Row 1 (class of trclass2), Table Data 2
Table Row 2 (id of trid4), Table Data 1 Table Row 2 (id of trid4), Table Data 2
Table Row 3, Table Data 1 Table Row 3, Table Data 2
Table Row 4 (class of trclass2), Table Data 1 Table Row 4 (class of trclass2), Table Data 2


$(function(){
  $('#btn11').on('click', function() {
    $('.testtable3 #trid4').siblings('.trclass2')
                           .css('backgroundColor', 'teal');
  });
});

Press the button below to action the above code:


Lesson 6 Complete

In this lesson we took our first look at how jquery simplifies navigation through the DOM using tree traversal.

Related Tutorials

jQuery 3.5 Basics - Lesson 7: Other Traversal

What's Next?

In the next lesson we take our second look at how jquery simplifies navigation through the DOM using miscellaneous traversal methods.