jQuery Multiple Selector: Target Several Elements

The jQuery multiple selector allows developers to combine several distinct selectors into a single query to target multiple DOM elements simultaneously. By using this feature, you can batch operations such as styling, event handling, or animations across different tags, classes, and IDs without duplicating code. This article explains how the multiple selector works, its syntax, and how to effectively apply it to simplify your JavaScript workflows.

Basic Syntax and How It Works

The multiple selector in jQuery borrows its syntax directly from CSS. To select multiple distinct elements at the same time, separate each individual selector with a comma , inside the jQuery wrapper function:

$("selector1, selector2, selectorN")

When this statement executes, jQuery evaluates each selector individually, retrieves the corresponding DOM elements, merges them into a single jQuery collection object, and automatically removes any duplicate nodes. The resulting matched elements are typically arranged in document order (the order in which they appear in the HTML source).

Common Examples

The multiple selector can combine any valid CSS selector types, including HTML tags, classes, IDs, and attribute selectors.

1. Targeting Different HTML Tags

$("h1, h2, p").css("font-family", "Arial, sans-serif");

This single line targets all <h1>, <h2>, and <p> elements on the page and updates their font family.

2. Combining IDs and Classes

$("#main-header, .sidebar, .footer").addClass("theme-dark");

Here, an element with the ID main-header and all elements carrying the classes sidebar and footer receive the theme-dark class in one operation.

3. Binding Event Listeners to Multiple Elements

$("button.submit, a.action-link").on("click", function(event) {
    event.preventDefault();
    console.log("Action triggered");
});

This applies the click event listener to both submit buttons and action links simultaneously, eliminating the need to write separate event bindings for each selector.

Key Benefits and Considerations

  • Cleaner, DRY Code: Consolidating selectors prevents the need to write redundant jQuery calls, keeping codebases concise and readable.
  • Batch Operations: Applying chained jQuery methods (such as .hide(), .fadeIn(), or .attr()) executes across the entire combined set in a single line.
  • Selector Independence: If one selector in the comma-separated list matches nothing in the DOM, jQuery continues processing the remaining valid selectors without throwing an error.