How to select element by its attribute using jQuery?

Here we are going to learn how to select HTML element by its attribute using jQuery.

Selecting element by its attribute with jQuery is also easy like selecting an element by its id or class. But there selecting by element by taking the attribute is slightly different than selecting by id or class.

In jQuery, we can select any element by its attribute value. Below is the syntax which shows how we can do that:


Now we are going to see an example.

Suppose we have the element which contains some text content:

<div attr="myAttr">
  The text color of this content is red by selecting this element by its attribute and then apply CSS color in jQuery.

In the above HTML code, we can see that we have set an attribute with its value. Now we are going to select the attribute in jQuery and then apply CSS color with jQuery css() method. Now below is our jQuery code:

     $("[attr=myAttr]").css("color", "red");

Now if we run our code, we will see the text content on the page colored red. From the red color of the text, we have confirmed that our jQuery code successfully able to select the element by its attribute value.

Clicking an element trigger to another element in jQuery

Detect change in HTML select tag and get changed value in jQuery

So we have seen how easy and simple to select an element by its attribute name and value. I hope you will try it also.

Leave a Reply

Your email address will not be published.