In the previous tutorials we have learned what are jQuery selectors and what is an element selector. In this guide, we will learn jQuery multiple elements selector.
Syntax
To select multiple elements of an html page using multiple elements selector, we pass the element names inside parenthesis, in double quotes, separated by commas.
$("element1, element2, element3")
For example: $(“div, p, h2”) this will select all the div, p and h2 elements of a page.
jQuery Multiple Elements Selector Example
In the following example we are selecting and changing the background colour of three elements (h2 heading element, a element, button element) on the button click event.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $("h2, a, button").css("background-color", "green"); }); }); </script> </head> <body> <h2>jQuery multiple elements selector example</h2> <p>This tutorial is published on <a href="https://beginnersbook.com">Beginnersbook</a> website</p> <h2>This is another h2 heading</h2> <button>Click Me!</button> </body> </html>
Output:
Before the button is clicked:
After the button is clicked:
Leave a Reply