Miscellaneous Traversal Methods

These methods provide other mechanisms for manipulating the set of matched DOM elements in a jQuery object.

Adds elements to the set of matched elements.

.add(selector)
.add(elements)
.add(html)

Checks the current matched set of elements against a selector and returns true if at least one of these elements matches the selector.

.is(selector)

Ends the most recent filtering operation in the current chain and returns the set of matched elements to its previous state.

.end()

Most of the methods in this chapter operate on a jQuery object and produce a new one, matching a different set of DOM elements. When this happens, it is as if a new set of elements is pushed onto a stack that is maintained inside the object. Each successive filtering method pushed a new element set onto the stack. If we need an older element set, we can use .end() to pop the sets back off of the stack.

Suppose we have a couple of short lists on a page:

The .end method is useful primarily when exploiting jQuery's chaining properties. When not using chaining, we can usually just call up a previous object by variable name, so that we don't need to manipulate the stack. With .end(), though, we can string all the method calls together:

This chain searches for items with the class foo within the first list only and adds the class some-class to them. Then .end() returns the object to its state before the call to .find(), so the second .find() looks for .bar inside <ul class="first">, not just inside that list's <li class="foo">, and adds the class another-class to the matching element. The result is that items 1 and 3 of the first list have a class added to them, and none of the items from the second list do.

A long jQuery chain can be visualized as a structured code block, with filtering methods providing the openings of nested blocks and .end methods closing them:

The last .end() is unnecessary, as we are discarding the jQuery object immediately thereafter. However, when the code is written in this form the .end() provides visual symmetry and closure—making the program, at least to the eyes of some developers, more readable.