jQuery multiple classes Selector
In jQuery, using the ".class" selector, we can select all the elements with a specific class. Whereas, we can also use the ".class" selector to select elements with multiple classes. To do so, we need to seperate each class with a (,) comma.
If we define a class name with a number, It may not work properly and may cause problems in some browsers.
Syntax
Following is the syntax to define multiple classes in jQuery −
$(".class1,.class2, ...")
Parameters
The '.class1.class2' is a string that specifies the classes to match. Each class is prefixed with a dot (.).
Example 1
This example selects the elements with the muliple classes "one", "two", and "three" and changes their background color to yellow −
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(".one, .two, .three").css("background-color", "yellow");
})
});
</script>
</head>
<body>
<p class="one">Paragraph element with (class "one").</p>
<p>This text won't be highlighted.</p>
<p class="two">Paragraph element with (class "two").</p>
<p>This text won't be highlighted.</p>
<p class="three">Paragraph element with (class "three").</p>
<button>Click</button>
</body>
</html
After clicking the button, the selected (paragraph) elements with class "one", "two", and "three" will be highlighted with a yellow background color.
Example 2
The following example hides the button elements with classes "one", "two", and "three" −
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$('.two, .three').hide();
})
});
</script>
</head>
<body>
<button class="one">Button 1</button>
<button class="two">Button 2</button>
<button class="three">Button 3</button>
<button class="four">Button 4</button>
<br><br>
<p>Click the below button...</p>
<button>Click</button>
</body>
</html>
when we click the button, all the button elements with classes "one", "two", and "three".