SyntaxStudy
Sign Up
jQuery jQuery Traversal Chaining and .end()
jQuery Intermediate 5 min read

jQuery Traversal Chaining and .end()

One of jQuery's most powerful features is method chaining — calling multiple methods sequentially on the same line. Each traversal method returns a new jQuery object representing the new selection. The .end() method steps back to the previous jQuery object in the chain, letting you work with multiple selections without breaking the chain or creating new variables.

Why .end() Matters

Without .end(), each traversal permanently changes the selection context for subsequent calls. With .end(), you can make targeted modifications to a sub-selection and then return to the original set to continue working — all within a single statement.

Practical Patterns

Use chaining with .end() to build readable single-statement blocks that modify multiple related elements: a container and its children, a list and its first item, or a form and a specific input.

  • .find().css().end() — modify descendants then return to parent
  • .filter().show().end().filter().hide() — split and style subsets
  • .addBack() — adds the previous set to the current one (union)
Example
// Chain: modify children then operate on parent
$('#notice')
    .find('strong')
        .css('color', 'red')
    .end()               // back to #notice
    .fadeIn(400);

// Filter two subsets, style each, return to full set
$('li')
    .filter('.done')
        .css('text-decoration', 'line-through')
    .end()
    .filter('.urgent')
        .css('font-weight', 'bold');

// addBack — include the original element with descendants
$('#sidebar')
    .find('p')
    .addBack()           // #sidebar + all p inside it
    .css('font-family', 'Georgia, serif');
Pro Tip

Indent each traversal level in your chain to make the navigation structure visually obvious for future readers.