In this article, we will go over Selecting Nodes by Attribute Value in jQuery.
In the previous articles, we have discussed about how to select elements by Tag Name, by ID and by Class Name. But there may be a time when it is not enough to find elements by these three. You may want to check specific attribute for a value and find elements based upon that value.
How to Select Elements by Attribute Value?
- Use brackets [attribute] to select based on attribute name and/or attribute value.
- Example: $(‘a[title]‘).
- The above selector will select all <a> elements that have a title attribute.
- $(‘a[title="Customer Info"]‘) will select all anchor elements that have a “Customer Info” title attribute.
Let's do an example of this. I want to find out all the divs where there is a title attribute. Let’s find out the count of them in an alert box. Right now, I have only one div with a title in the web page. I can use $(‘div[title]‘) to find all the divs which have a title.
Go ahead and run it and we will get 1 in the alert box.
Now let’s try to find a specific one. We want to find a div where title equals Div Title. At first look, you may think why should we do like this. Because the div has an Id and we can select it by Id which is the fastest way. But in an actual web page, there may be many divs having the same title. We want to find all those divs. Then put them in a divs collection. Wrap it inside an alert to find their count.
While running the application, we will get 1 as output, which is true as well as we have only one div with title Div Title.
Now let’s change the title from Div Title to div Title inside the Selector. That is, change the case of one letter.
Go ahead and run it and we can see the output as 0. What did you understand from this? Selecting Nodes by Attribute value is case sensitive.
Then let’s try to find the input tags. I want to find input tags whose type is text. You can use $(‘input [type="text"]‘) for this purpose. Wrap it up inside an alert to find its length.
While scrolling down our web page, at the bottom of the form, we can see 2 input tags whose type is text.
Go ahead and run the application and we will get 2 as output as expected.
Now let’s change the background color of input tags whose type is text to yellow.
While running the application, we can see the background color of both the two text boxes are changed to yellow.
From the above example, you can see how easy it is to select elements by attribute value using jQuery.