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:

Example: Selecting multiple classes


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.