Home »
jQuery »
jQuery Examples
Selecting multiple classes with jQuery
In this tutorial, we will learn how to select multiple classes by using the .class selector using jQuery?
Submitted by Pratishtha Saxena, on July 08, 2022
Selecting multiple classes in jQuery can be done very easily. Using the .class selector many different classes can be considered in a single line and together other functions can be performed on it. The classes are written with a dot (.) operator and they are separated by a comma in between.
Syntax:
$(".class1, .class2, .class3, ...");
It is sometimes important to list all the HTML elements using class (or some other attribute like id) so that the operation that has to be executed on all the classes can be done combinedly. In this way, a lot of manual work can be prevented.
Suppose we wish to change or apply some CSS on let's say three classes instead of all given classes. So, for this, we can select those particular three classes that we want to work on and then apply the functions to them.
Example:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<center>
<h1 class="one">This is h1 tag.</h1>
<p class="two">This is paragraph one.</p>
<p class="three">This is paragraph two.</p>
<div class="four">This is div tag.</div>
<p class="five">This is paragraph three.</p>
</center>
</body>
</html>
jQuery Function:
<script>
$(document).ready(function() {
$(".one, .three, .five").css(
"background-color", "skyblue");
$(".two, .four").css(
"background-color", "yellow");
});
</script>
Output: