Last Updated on September 11, 2022 by Roshan Parihar
Learn how to get element by class using jquery .class selector. Find the HTML element by class and apply effect, CSS, and other useful jQuery methods.
In this tutorial, you will learn how to get elements using the class of the element and the jquery selector. Let’s find out with the examples given below.
How to Get Element By Class and Find Element with Single Class
To get the element by class in jQuery, you have to use the value of the class
attribute of the element. Add that value to the jQuery selector with a dot(.) before the name.
In the below example first, select the element by class. After that, uses the jQuery css()
function to apply CSS to the selected element.
1 2 3 4 5 6 |
<script> $(document).ready(function(){ $('.myPara').css('color','blue'); }); </script> <p class="myPara">This is a simple paragraph.</p> |
Output
This is a simple paragraph.
The above example contains the text content with class myPara
. To select the element, it uses this class with a dot (.) before the class name. It gives access to the HTML element to apply the jQuery methods.
Find Elements with Two Classes
If you have elements with the same class name, you can access the required element using the other class. Suppose each element has the same classes in three paragraphs and you want to find only the required HTML element.
Add the two classes with a dot (.) before the class name without any space. You can use the second class with the HTML element as given below.
1 2 3 4 5 6 7 8 |
<script> $(document).ready(function(){ $('.myOne.myTwo').css('color','red'); }); </script> <p class="myOne">First paragraph to show you the get element method.</p> <p class="myOne myTwo">Second paragraph to show you the get element method.</p> <p class="myOne">Third paragraph to show you the get element method.</p> |
Output
First paragraph to show you the get element method.
Second paragraph to show you the get element method.
Third paragraph to show you the get element method.
The above example contains three paragraphs with the same class with a different class in the middle paragraph. It uses .myOne.myTwo
to select the required class.
You May Also Like to Read
- How to Get Selected Radio Button Value Using jQuery
- jQuery Get Selected Option Value on Select
- How to Get Selected Checkbox Value Using jQuery
Reference