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 :
<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 :
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.
Also check : How to select elements in jQuery
Try the new comma separated selectors in your new assignment. codippa !!!0