In this tutorial, we will learn jQuery class Selector with examples. If you wondering what is a selector, refer my detailed guide on jQuery Selectors.
jQuery class Selector Syntax
$ sign followed by parenthesis and class name mentioned in the parenthesis prefixed with a . (dot).
$(".myclass")
This will select all the elements with the class value as myclass
jQuery class Selector Example
In the following example we have marked three elements with the class value cl
, we have marked h2 element, p element and the button element with class cl
.
In the jQuery function, on the button click event we are selecting and then changing the background colour of those elements that have the class value equals to cl
. Since we have three elements with this class, the background of these elements are changed when the button is clicked.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ $(".cl").css("background-color", "green"); }); }); </script> </head> <body> <h2 class="cl">jQuery class selector example</h2> <p class="cl">This jQuery class selector example is published on beginnersbook.com</p> <p>Class selector selects all the elements that has the specified class</p> <button class="cl">Click Me!</button> </body> </html>
Output: The following two screenshots are taken before and after clicking the Click Me! button.
Before clicking the button:
After clicking the button:
Leave a Reply