Other Traversal JQ Home  <<  JQ Basics  <<  Other Traversal

In this lesson we finish our investigation of how jQuery simplifies navigation through the DOM, by looking at the methods available for navigating the DOM that are not hierarchial.

Other Traversal Methods Description
.add()Add specified elements to the matched set.
.addBack()Add the previous set of elements on the jQuery stack to the current set of elements.
.andSelf() **REMOVED**
Add the previous set of elements on the jQuery stack to the current set of elements.
.contents()Retrieve the children of each element within the matched set, including text and comment nodes.
.each()Iterate over a jQuery object, executing a function for each element within the matched set.
.end()End the most recent filtering operation in the current execution chain and return the matched set of elements to its previous state ( prior to the most recent filter being applied ).

The jQuery Stack

The jQuery stack is used by several methods within this lesson so now is a good time to explain what it is and does. When we chain our traversal or filtering methods together, many of the jQuery methods used operate on an existing jQuery instance and produce a new jQuery object that match a different set of elements. jQuery maintains the previous set of elements, as well as the new set of elements as an internal stack. We can visualize this stack where the newest set of elements is 'pushed' onto the stack. As we continue through our jQuery chain, each new traversal or filtering method will create a new set of elements that gets 'pushed' onto the stack.

The .add() Method Top

Add specified elements to the matched set.

We will be using the .add( selector [, context ] ) signature for our example which adds the specified selector elements to the matched set optionally using a DOM Element, Document, or jQuery object as a context.

The second signature .add( element ) will add the specified elements to the matched set.

The third signature .add( html ) will add the specified HTML to the matched set.

The fourth signature .add( jQuery object ) will add the specified jQuery object to the matched set.

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

In the example below when the left button is pressed we select the list item with an id of 'list1' and add the list item with an id of 'list2' to it. We then turn the background colour to orange.

When the right button is pressed we create a jQuery object of elements with an id of 'list2'. We then use this context when we add our elements with a class of 'class1'. Therefore only the elements from 'list2' are included in the union and not the elements from 'list3'. We then turn the background colour to yellow.

  • Shopping List  (id of list1)
    • Tin of Tomatoes
    • Bacon
    • Loaf of Bread
  • Party Guest List  (id of list2)
    • Bruce Wayne  (class of class1)
    • Emily Bronte
    • Alma Walcott  (class of class1)
  • Wish List  (id of list3)
    • Health  (class of class1)
    • Wealth
    • Happiness  (class of class1)


$(function(){
  $('#btn1').on('click', function() {
    $('#list1').add('#list2')
               .css('backgroundColor', 'orange');
  });
  $('#btn2').on('click', function() {
    var $list2 = $('#list2');
    $('#list1').add('.class1', $list2)
               .css('backgroundColor', 'yellow');
  });
});

Press the button below to action the above code:

            

The .addBack() Method Top

Add the previous set of elements on the jQuery stack to the current set of elements, optionally filtered by a selector.

In the example below when the left button is pressed we select all preceding 'tr' elements within the table that come before the 'tr' element with the class of 'trid1 and then change the background colour to orange within the matched set. This will select all 'tr' elements within the table that come before the last 'tr' element with the class of 'trid1' (first 3 rows).

When the middle button is pressed we select all preceding 'tr' elements within the table that come before the 'tr' element with the class of 'trid1. We then add the previous item on the stack using .addBack() (our original selection) and then change the background colour to teal within the matched set. Notice that now all table rows are changed.

When the right button is pressed we select all preceding 'tr' elements within the table that come before the 'tr' element with the class of 'trid1. We then add the previous item on the stack using .addBack('#trid1') (our original selection filtered by a selector) and then change the background colour to red within the matched set. Notice that all table rows are changed to a red background except the last row as this doesn't have an id of '#trid1'.

Table For Testing The .addBack() Signature
Table Row 1, Table Data 1 Table Row 1, Table Data 2
Table Row 2, Table Data 1 Table Row 2, Table Data 2
Table Row 3, (row class and id of trid1), Table Data 1 Table Row 3, (row class and id of trid1), Table Data 2
Table Row 4, (row class of trid1), Table Data 1 Table Row 4, (row class of trid1) Table Data 2


$(function(){
  $('#btn3').on('click', function() {
    $('.testtable .trid1').prevAll()
                          .css('backgroundColor', 'orange');
  });
  $('#btn4').on('click', function() {
    $('.testtable .trid1').prevAll()
                          .addBack()
                          .css('backgroundColor', 'teal');
  });
  $('#btn10').on('click', function() {
    $('.testtable .trid1').prevAll()
                          .addBack('#trid1')
                          .css('backgroundColor', 'red');
  });
});

Press the button below to action the above code:

                           

The .andSelf() Method **DEPRECATED**Top

Add the previous set of elements on the jQuery stack to the current set of elements.

This method was deprecated in jQuery 1.8 and removed in 3.0 and is now used as an alias for the .addBack() method above which was added in jQuery 1.8.

The .contents() Method Top

Retrieve the children of each element within the matched set, including text and comment nodes.

In the example below we select all 'a' elements on the page. We then further filter to find non ELEMENT_NODE children. We then get the parent of each element in the matched set and turn the background colour to orange.

You can also get the content document of an iframe that is on the same domain as the page we are using it in. An example of this is available in the reference section.


$(function(){
  $('#btn5').on('click', function() {
    $('a').contents()
          .filter(function(){ 
            return this.nodeType != 1; // Any node type apart from ELEMENT_NODE 
          })
          .parent()
          .css('backgroundColor', 'orange');
  });

Press the button below to action the above code:

The .each() Method Top

Iterate over a jQuery object, executing a function for each element within the matched set.

We will be using the .each( function(index, Element) ) signature for our example which iterates over a jQuery object, executing a function for each element within the matched set.

We can also use the jQuery object instead of DOM elements by using the $(this) syntax within a signature of .each( function() ) as explained in the reference section.

In the example below when we press the left button we select all 'td' elements within the table, iterate over the collection changing the background colour to orange.

When we press the right button we select all 'td' elements within the table, iterate over the collection changing the background colour to yellow. We break from the loop when we hit the 'td' element with the id of 'tdid1'.

Table For Testing The .each( function(index, Element) ) Method
Table Row 1, Table Data 1 Table Row 1, Table Data 2
Table Row 2, Table Data 1 Table Row 2, Table Data 2
Table Row 3, Table Data 1 (id of tdid1) Table Row 3, Table Data 2
Table Row 4, Table Data 1 Table Row 4, Table Data 2


$(function(){
  $('#btn6').on('click', function() {
    $('.testtable2 td').each(function (index, tableElement) { // tableElement == this
      $(tableElement).css('backgroundColor', 'orange'); 
    });
  });
  $('#btn7').on('click', function() {
    $('.testtable2 td').each(function (index, tableElement) { // tableElement == this
      $(tableElement).css('backgroundColor', 'yellow'); 
      if ($(this).is('#tdid3')) {
        return false; // break out of the loop
      }
    });
  });
});

Press the button below to action the above code:

             

The .end() Method Top

End the most recent filtering operation in the current execution chain and return the matched set of elements to its previous state ( prior to the most recent filter being applied )

When we chain our traversal or filtering methods together, many of the jQuery methods used operate on an existing jQuery instance and produce a new jQuery object that match a different set of elements. jQuery maintains the previous set of elements, as well as the new set of elements as an internal stack. We can visualize this stack where the newest set of elements is 'pushed' onto the stack. As we continue through our jQuery chain, each new traversal or filtering method will create a new set of elements that gets 'pushed' onto the stack. The .end() method allows us to 'pop' the most recent set of elements off the stack.

In the example when the left button is pressed we create a matched set of the elements of the list item marked with an id of 'id1' and change the background colour to yellow. We then further filter this set using a class selector of '.class1' and turn the background colour to orange.

When the right button is pressed we create a matched set of the elements of the list item marked with an id of 'id1' and change the background colour to olive. We then use the .end() method to 'pop' the set we created off the stack. This returns us to a matched set that includes all elements within the selector '.content ol'. Thus when we do the next .find() using a class selector of 'class1' and turn the background colour to teal, the other list item with a class of 'class1' is also selected.

Notice how we don't indent the .end() method and place it under the other methods. This is purely a matter of taste but if you have a long method chain it makes the code more readable.

  1. Things To Do When I Get Up  (id of id1)
    1. Put The Kettle On  (class of class2)
    2. Put The Teabag in The Cup
    3. Wait for Kettle To Boil
    4. Pour Boiling Water In The Cup
  2. Things To Do When I Go To Bed  (id of id2)
    1. Turn Stuff Off  (class of class2)
    2. Put The Cat Out
    3. Lock The Doors
    4. Brush My Teeth


$(function(){
  $('#btn8').on('click', function() {
    $('.content ol').find('#id1')
                 .css('backgroundColor', 'yellow')
                 .find('.class2')
                 .css('backgroundColor', 'orange');
  });
  $('#btn9').on('click', function() {
    $('.content ol').find('#id1')
                 .css('backgroundColor', 'olive')
      .end()
                 .find('.class2')
                 .css('backgroundColor', 'teal');
  });
});

Press the button below to action the above code:

             

Lesson 7 Complete

In this lesson we looked at the miscellaneous DOM traversal jQuery methods.

Related Tutorials

jQuery Basics - Lesson 6: Tree Traversal

Reference

Methods

Attributes and Properties - .css() method
Events - .on() method
Filtering - .filter() method
Filtering - .is() method
Tree Traversal - .children() method
Tree Traversal - .find() method
Tree Traversal - .parent() method
Tree Traversal - .prevAll() method
Other Traversal - .add() method
Other Traversal - .andSelf() method
Other Traversal - .closest() method
Other Traversal - .each() method
Other Traversal - .end() method