Learn all about the jQuery function .add().
Given a jQuery object that represents a set of DOM elements, the
.add() method constructs a new jQuery object from the union of those elements and the ones passed into the method. The argument to
.add() can be pretty much anything that
$() accepts, including a jQuery selector expression, references to DOM elements, or an HTML snippet.
Do not assume that this method appends the elements to the existing collection in the order they are passed to the
.add() method. When all elements are members of the same document, the resulting collection from
.add() will be sorted in document order; that is, in order of each element’s appearance in the document. If the collection consists of elements from different documents or ones not in any document, the sort order is undefined. To create a jQuery object with elements in a well-defined order and without sorting overhead, use the
The updated set of elements can be used in a following (chained) method, or assigned to a variable for later use. For example:
The following will not save the added elements, because the
.add() method creates a new set and leaves the original set in pdiv unchanged:
Consider a page with a simple list and a paragraph following it:
We can select the list items and then the paragraph by using either a selector or a reference to the DOM element itself as the
.add() method’s argument:
The result of this call is a red background behind all four elements. Using an HTML snippet as the
.add() method’s argument (as in the third version), we can create additional elements on the fly and add those elements to the matched set of elements. Let’s say, for example, that we want to alter the background of the list items along with a newly created paragraph:
Although the new paragraph has been created and its background color changed, it still does not appear on the page. To place it on the page, we could add one of the insertion methods to the chain.
As of jQuery 1.4 the results from .add() will always be returned in document order (rather than a simple concatenation).