Skip to content
Related Articles

Related Articles

Difference between ID and Class Selector in jQuery

View Discussion
Improve Article
Save Article
  • Last Updated : 12 Jul, 2022
View Discussion
Improve Article
Save Article

jQuery ID Selector: The #id selector specifies the id for an HTML element to be selected. It should not begin with a number and the id attribute must be unique within a document which means it can be used only one at a time.

Syntax:

$("#id")
  • id is the element’s specific id.

Example: The following code demonstrates the jQuery ID selector.

HTML




<!DOCTYPE html>
<html>
    
<head>
    <script src=
   </script>
       
    <script>
        $(document).ready(function() {
           $("#paraID").css("background-color","red");
        });
    </script>
</head>
    
<body>  
    <h1 style="color:green">GeeksforGeeks</h1>
    
    <p id="paraID">
       jQuery #id selector is used for this p element.
    </p>
    
</body>  
</html>


Output:

 

jQuery class Selector: The .class selector specifies the class for an element to be selected. It should not begin with a number. It gives styling to several HTML elements.

Syntax:

$(".class")
  • class is the name of the class given for the HTML elements.

Example: The following code demonstrates the jQuery class selector.           

HTML




<!DOCTYPE html>
<html>
    
<head>
    <script src=
   </script>
    <script>
      $(document).ready(function() {
        $(".pClass").css("background-color", "blue");
      });
    </script>
</head>
    
<body>
    <h1 style="color:green">GeeksforGeeks</h1>
    
    <p class="pClass">
       jQuery.class selector is used for p element
    </p>
  
    
    <span class="pClass">
       jQuery.class selector is used for span element
    </span>  
</body>  
</html>


Output:

 

Differentiate the concepts of ID selector and class selector: The only difference between them is that “id” is unique in a page and it is applied to one HTML element while “class” selector can apply to multiple HTML elements. 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!