A jQuery .class selector selects all the elements for the specified class name. You can apply CSS or any other effects with jQuery by selecting single or multiple elements using the class name.
The class name is the value of the class attribute of the required HTML element.
JQuery .class Selector
To select an element, you have to find the class attribute of the element. After that, use the dot(.) before the class name as in the syntax given below.
Syntax
1 |
$(.classname) |
Let’s see the example to select an element and apply the CSS using jQuery.
Example
1 2 3 4 5 6 7 8 |
<script> $(document).ready(function(){ $(".myred").css("color", "red"); }); </script> <p>Welcome to the tutorial world.</p> <p class="myred">Tutorialdeep is the best way to learn jQuery.</p> <em>You are learning jQuery.</em> |
Output
Welcome to the tutorial world.
Tutorialdeep is the best way to learn jQuery.
You are learning jQuery.
The above example applies the red color to the specified class in the jquery class selector. However, this is for the single class to select only the single element. You can apply the color to more than one element by learning the next example.
Select Multiple Classes Using jQuery
If you want to apply the color or any other effect to more than one element at one go. You have to use the jQuery multiple class selector.
See the syntax given below to get the use of multiple class selectors.
Syntax
1 |
$(.classname1, .classname2, .classname3...) |
Let’s create an example to add multiple classes using the above syntax. It applies the same color to more than one element with different class names.
Example
1 2 3 4 5 6 7 8 |
<script> $(document).ready(function(){ $(".mytutorial, .myjquery").css("color", "green"); }); </script> <p class="mytutorial">Welcome to Tutorial! A best place to improve technical skills.</p> <p>It is the best place to learn web development and coding skills.</p> <p class="myjquery">You are learning jQuery.</p> |
Output
Welcome to Tutorial! A best place to improve technical skills.
It is the best place to learn web development and coding skills.
You are learning jQuery.
Learn jQuery with live examples.
The above example applies the green color to the multiple specified classes using the css().