How to select element by its attribute using jQuery?

In this tutorial, you will learn how to select an HTML element by its attribute using jQuery.

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

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

$("[attribute=attributeValue]")

Now we are going to see an example.

Suppose we have an HTML element that contains some text content as you can see below:

<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.
</div>

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

<script>
  $(document).ready(function(){
     $("[attr=myAttr]").css("color", "red");
  });
</script>

Now if we run the above code in our browser, 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. I hope you will try it also.

Leave a Reply

Your email address will not be published. Required fields are marked *