find dom element using attribute value

How to Find DOM Element Using Attribute Value

Web developers frequently need to select DOM elements to perform one task or the other with them. JavaScript allows you to easily select these elements using their ID, class, or names. But sometimes you may need to find DOM element using attribute value. In this article, we will learn how to do this.


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.

$('[data-text="hello"]');

Luckily most modern browsers have started supporting function querySelectorAll() that allows you to select DOM element using attribute value. Here is its syntax.

document.querySelectorAll('[attribute="value"]');

Here is how to use it.

document.querySelectorAll('[data-text="hello"]');

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.

document.querySelector('[data-text="hello"]');

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.

Also read:

How to Generate Hash from String in JavaScript
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

Leave a Reply

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