jQuery - Concept of Traversal in jQuery

1. Concept of Traversal in jQuery

In jQuery, you often start with a set of elements and then traverse to find other elements. For example:

$('div')          // selects all divs
    .find('p');   // finds all <p> inside those divs

At this point, your current set of elements is now the <p> elements inside the <div>. The original <div> selection is lost if you continue chaining.


2. Reversing Traversal with .end()

The .end() method goes back to the previous selection set—essentially undoing the last traversal.

Syntax:

.previousTraversal.end()
  • .end() returns the previous jQuery object from the chain before the last destructive traversal (like .find(), .children(), .parent()).


3. Example

$('div')           // Step 1: select all divs
    .find('p')     // Step 2: select all <p> inside those divs
    .css('color', 'red') // Step 3: style <p> elements
    .end()         // Step 4: go back to original <div> selection
    .css('border', '1px solid blue'); // Step 5: style <div> elements

Explanation:

  1. $('div') → selects all <div> elements.

  2. .find('p') → changes the current selection to <p> elements inside those <div>.

  3. .css('color', 'red') → applies CSS to <p> elements.

  4. .end() → goes back to the <div> elements (undoes .find('p')).

  5. .css('border', '1px solid blue') → applies CSS to <div> elements.

So .end() allows you to reverse a traversal and continue chaining on the previous set of elements.


4. Key Points

  • .end() reverts to the previous set of elements in the chain.

  • You can chain multiple .end() calls to go back several steps.

  • Very useful when you want to operate on both the traversed elements and the original elements without creating new variables.