Selecting elements using Class selector

In this post of JQuery, I will show how to select elements using class selector.

Class selector is used to retrieve elements whose class attribute’s value matches with the one specified in the selector.

Class selector also selects elements whose class attribute’s value have multiple class name and one of them matches with the one specified in the selector.

This selector is similar to JavaScript getElementsByClassName() method.

The syntax is “.” operator followed by class name to be searched for. For eg


$('.class1');

In the above example we are telling JQuery to
1) select all the elements whose attribute class’s value matches with “class1” and
2) select all the elements whose attribute class’s value have multiple class name and one of them matches with “class1”.

Below is the complete html code


1  <html>
2   <head>
3       https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
4   </head>
5   <body>
6       
7           function selectAll() {
8               var $element = $('.class1');
9               alert($element);
10          }
11      
12      <input id="button" name="button" type="button" value="button" onclick="selectAll();"/>
13      <br>
14      <a class="class1">www.google.com</a>
15      <br>
16      <a class="class2">www.rediff.com</a>
17      <br>
18      <a class="class1 class3">www.yahoo.com</a>
19  </body>
20 </html>

In the above code when the javascript method selectAll is called elements at line 14 and 18 will be selected and returned by $(.class1) method as a collection.

If we want to select elements whose attribute class’s value is “class1 class2” (a combination of class1 and class2), then the syntax of the class selector will be
$(‘.class1.class2’)

Leave a Reply