How to select multiple elements in jQuery / How to use single expression to select multiple elements in jQuery

Every web page has multiple elements. A typical jQuery script selects different elements and performs operations on them. Every element has different selector such as id, name, class etc. It would be nice if one is able to select multiple elements in one expression only. Let’s see how.

Suppose a page has following elements :

<div id=”headerDiv”>coDippa</div>

<span id=”tagline”>the website</span>

<p class=”desc”>want some code!!!</p>

If you want to perform the same operation on all the above elements such as setting their background color or changing the font size of their text content, then you would require three separate lines of code. These three lines will have the same code, only the selector would differ as :

$(“#headerDiv”).css(‘background-color’,’red’);

$(“#tagline”).css(‘background-color’,’red’);

$(“.desc”).css(‘background-color’,’red’);

See!!! The above three lines have the same repeating code. Only the selector of elements differ. It would be handy if there was a way to provide multiple selectors in a single statement at once. Luckily, there is a way in jQuery to provide multiple selectors in one statement using comma as a separator. Thus, all the above elements can be selected as :

$(“#headerDiv, #tagline, .desc”)

Therefore, above three lines of code can be reduced to

$(“#headerDiv, #tagline, .desc”).css(‘background-color’,’red’);

Isn’t it cool !!!

It should be remembered that when multiple selectors are given in this way then same code is executed on all those elements. Thus in above example, background color of all the elements turns to red.

Try the new comma separated selectors in your new assignment. codippa !!!

2 Comments

Leave a Reply