Select element by its attribute in jQuery

By Faruque Ahamed Mollick

Selecting an element by its attribute is possible and it is so easy also in jQuery. Now we are going to see how to select an element by the attribute using jQuery.

At first, let’s see the syntax of attribute selector in jQuery:

$("[attribute_name=attribute_value]")

Now suppose we want to select our div element with the attribute name “my_ttribute” and the attribute value “my-attribute-value”. Below is that div element:

<div my_ttribute="my-attribute-value" style="width: 100px;height: 100px;"></div>

Now we are going to select our div element by its attribute with jQuery attribute selector. Below is the code that will select the element by its attribute:

$('[my_ttribute="my-attribute-value"]')

Now suppose we want to change the background color of the div element. As we have set the width and height of our element, so we can see the background color. Below is the jQuery code which will set the background color to our element:

$('[my_ttribute="my-attribute-value"]').css('background','green');

How to reload an iframe in jQuery?

Disable right click, copy, cut on web page using jQuery

Set the input value by selecting attribute of input field in jQuery

Now we are going to see another example where we will set the input value by selecting the attribute of an input field.

Below is the HTML of our input field:

<input type="text" attr="my_attr">

Now below is the jQuery code which will set a value to our input field and the input field will be selected by the attribute. Below is the jQuery code:

$('[attr="my_attr"]').val('This is the input value');

How to stop JavaScript setInterval() after a certain time period?

Simple Animation Example Using jQuery

Applying click method to the element by attribute selector:

Now we are going to apply click method by selecting the element by its attribute. Below is our button:

<button btnattr="myBtn">Click me</button>

And below is our jQuery code:

$( '[btnattr="myBtn"]' ).click(function() {
  alert( "Click method with attribute selector in jQuery" );
});

Now we can see the alert message when we click the button. Here we have applied the jQuery click method by selecting the button with its attribute.


So, in this post, we have seen how to select an element with its attribute value.

Leave a Reply

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