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.
[js]$("selector1, selector2,…selectorN"); //Correct Syntax
$("selector1", "selector2",…"selectorN"); //Incorrect Syntax[/js]
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.
border:1px solid #E3E3E3;
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.
[js]$(‘.CSSclass1, .CSSclass2′).css(‘border’, ’1px solid #E3E3E3′);[/js]
You can also combine any kind of selectors.
[js]$(‘.CSSclass1, p, h1, #divId1, div .selectedDiv, input[type=text]‘).addClass(‘borders’); [/js]
In the example, we selected
- All elements with class CSSclass1
- All paragraph element (p).
- All h1 elements
- An element with ID divID1
- All div elements with class .selectedDiv
- 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.