How to Find DOM Element Using Attribute Value
Let us say you have the following DOM element.
<div id='myDiv' class='myClass' data-text='hello'> ... </div>
Let us say you need to select the above div using attribute value data-text. If you are using jQuery, then it is super easy to do it as shown below.
Luckily most modern browsers have started supporting function querySelectorAll() that allows you to select DOM element using attribute value. Here is its syntax.
Here is how to use it.
The above command will select all DOM elements with data-text=’hello’. Please remember to wrap attribute=value within square brackets […] above.
If you want to select only the first element with attribute value, use querySelector() function instead.
In fact, you can even use these functions to select DOM elements based on class names.
document.querySelectorAll('.myClass'); OR document.querySelector('.myClass');
Please note the difference between using attributes and classes in selectors. Attributes need to be wrapped in square brackets while class names should not be. But class names need to be prefixed with a dot(.). This is similar to the syntax used for jQuery selectors.
In this article, we have learnt how to select DOM element using attribute.
How to List Properties of JS Object
How to Detect if Device is iOS
How to Count Character Occurrence in JS String
How to Add Auto Increment ID to MySQL Table