How to select multiple DOM elements with jQuery

We had a series of articles explaining various ways of selecting the DOM elements with jQuery.  We read about basic and hierarchical selectors, DOM filters and a special case of form filters. We saw an example of multiple selections in the post about the basic and hierarchical selectors. It is a very common requirement to select multiple elements from unrelated areas on the web page. So, today, we will read more about the topic of selecting multiple DOM elements.

Generalized Syntax of selecting multiple DOM elements with jQuery

The multiple elements can be selected by comma separating the selectors in a single argument.

$("selector1, selector2,…selectorN"); //Correct Syntax

$("selector1", "selector2",…"selectorN"); //Incorrect Syntax

where selector1, selector2, … selectorN are any valid jQuery DOM selectors. You can pass any number of valid selectors to the jQuery wrapper. But, the selectors are to be passed as a single comma separated argument.

Examples of selecting multiple DOM elements with jQuery

You can use any combination of valid selectors. Let’s start with a basic selection of all DOM elements with any of the two CSS classes. The elements are selected to perform some action on them. So, we will apply border to the selected elements.

<style>

.borders {

border:1px solid #E3E3E3;

</style>

…

$('.CSSclass1, .CSSclass2').addClass('borders');

The snippet just shows the sections required for this example. It is advised to put the CSS in separate file.

However, with the use of .css function, you can directly apply the CSS to the selected elements.

$('.CSSclass1, .CSSclass2').css('border', '1px solid #E3E3E3');

You can also combine any kind of selectors.

$('.CSSclass1, p, h1, #divId1, div .selectedDiv, input[type=text]').addClass('borders'); 

In the example, we selected

  1. All elements with class CSSclass1
  2. All paragraph element (p).
  3. All h1 elements
  4. An element with ID divID1
  5. All div elements with class .selectedDiv
  6. All input elements of text type

The statement applies the borders class to all the selected elements.

We will continue to explore other useful ways of selecting the DOM elements.