Add Elements to a jQuery Selection with add()

The jQuery .add() method allows developers to expand an existing matched set of DOM elements by adding additional elements to it. This guide explains how the .add() method works, its syntax, how it handles element ordering, and provides clear code examples demonstrating how to combine elements, selectors, and HTML snippets into a single jQuery collection.

Understanding the .add() Method

The .add() method creates and returns a new jQuery object containing the elements from the original selection plus the new elements you specify. It does not modify the original jQuery object in place, which means you must either chain additional methods to it directly or assign the result to a new variable.

Syntax and Accepted Parameters

.add( selector [, context ] )
.add( elements )
.add( html )
.add( selection )

The method accepts several types of arguments:

  • Selector string: A CSS selector matching elements already in the document.
  • DOM elements: One or more raw JavaScript DOM nodes.
  • HTML string: A snippet of HTML to be created on the fly and added to the set.
  • jQuery object: An existing jQuery collection to merge with the current one.

Practical Examples

1. Adding Elements by Selector

To combine multiple distinct CSS selectors into one set dynamically:

// Select all paragraph elements, then include all h2 elements
var content = $("p").add("h2");

// Apply a styling change to both <p> and <h2> elements
content.css("color", "#333333");

2. Adding an Existing DOM Element

You can pass a native JavaScript DOM reference directly into the method:

var footer = document.getElementById("site-footer");

// Select the header, add the footer element, and apply a class
$("header").add(footer).addClass("highlight");

3. Adding Newly Created HTML

You can generate new markup on the fly and add it to an existing selection:

// Select existing list items and add a new dynamic list item to the set
$("ul.menu li").add("<li>New Item</li>").appendTo("ul.menu");

4. Combining Two jQuery Objects

If you already have two separate selections, you can combine them cleanly:

var buttons = $("button.primary");
var links = $("a.btn");

var allClickables = buttons.add(links);
allClickables.attr("disabled", true);

Document Order Behavior

When using .add() to combine elements existing in the DOM, jQuery automatically sorts the combined collection according to their order in the document, rather than the order in which they were added. If you add newly created HTML nodes that are not yet in the document, those elements are appended to the end of the collection.