This tutorial will describe the procedure for finding the DOM element based on any attribute value.
How to Find/Retrieve an Element in DOM Based on an Attribute Value?
To find the element in DOM based on an attribute value, utilize the “querySelector()” method. It gives the first element found in the document that matches the given CSS selector value.
Note: For getting all the elements that match the specified selector value, use the “querySelectorAll()” method.
Syntax
For using the “querySelector()” method, utilize the following syntax:
Here, the selector will be an id or class as “#id”, “.class”:
You can also use the given syntax for finding the element based on attribute value:
In the above syntax, “selector” will be “id” or “class”, or the “value” will be “idName” or “className”.
Example
In an HTML file, create a div element that contains a heading using h4 element, a plain text using <span> tag, and a div for a message with assigned id “message”:
The page will look like as follow:
Now, we will get the element where the id “message” is assigned using the “querySelector()” method:
Finally, print the element on the console:
In the output, the “div” element is shown with its assigned id “message”, which indicates that the required element has been successfully retrieved:
You can also get the element using the given syntax. Here, we will get the element whose id is “msg”:
Output
Now, update the color of it using the “style” property:
As you can see, the text was in “green” color, and now it has been updated to “blue”:
That’s all about finding an element in a DOM based on an attribute value.
Conclusion
For finding an element in DOM based on an attribute value, utilize the “querySelector()” method that gives the first element in the document that matches the specified CSS selector value. Moreover, to get all the elements that match the specified selector value, use the “querySelectorAll()” method. This tutorial described the procedure for finding the DOM element based on any attribute value.