jQuery select by class name allows us to find a specific HTML element with the value of its class attribute.
jQuery select by class
Here is the general syntax for using the jQuery select by class name:
$(".classname")
ID could be any value provided in the id attributes of the HTML element. You should use period character ( .) followed by the class name specified in the html element.
$(".myClass")
: This will select all HTML elements with class name equal to “myClass”.
For example if there is a HTML element in the document like <div class="myClass"> some text </div>
, $(“.myClass”) will select this div and do the intended action on it. All the manipulations will affect only the elements specified with the given class name in the selector.
jQuery select by class example
This example demonstrates the use of jQuery select by its class name and changing the CSS style of the selected element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<html> <head> <title>jQuery select by Class</title> <style> div, span { width: 130px; height: 50px; float: left; padding: 15px; margin: 15px; background-color: #EEEEEE; } </style> <script src="https://code.jquery.com/jquery-3.2.1.js"></script> </head> <body> <div class="class1">div element className="class1"</div> <div class="class2">div element className="class2"</div> <span class="class3">span element className="class3"</span> <script> $( ".class2" ).css( "border", "5px solid green" ); </script> </body> </html> |
You can see that <div> element with class=”class2″ is selected for manipulation and some other styles are added to it.
Below image shows the output page rendered by the browser.
jQuery Select by Class Demo
jQuery select by class summary
jQuery class selector makes it easy to apply CSS class to any number of elements in the html document. This selector is very helpful in keeping uniformity of certain elements.