Sometimes, we want to select one or more elements in the DOM that has the given attribute and value.
In this article, we’ll look at how to select one or more elements in the DOM based on an attribute value.
Select One or More Elements in the DOM Based on an Exact Attribute Value
To select one or more elements in the DOM based on an attribute value, we can pass a selector into querySelector
to select one element with the given attribute value.
To select all the elements with the given attribute value, we can use the querySelectorAll
method.
The general format of the selector is:
tagName[attribute="value"]
For instance, if we want to select one element with an image with the given src
attribute value given the following HTML:
<img src='https://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg'>
We can write:
const img = document.querySelector("img[src='https://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg']");
console.log(img)
We call querySelector
with the tag name img
,
And the src
attribute value is https://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg
.
This will select the first element with the given tag name and attribute value.
If we want to select all elements with the given tag name and attribute value, we can replace querySelector
with querySelectorAll
.
Select One or More Elements in the DOM Containing a Given Attribute Value
We can add a ~
before the =
sign to get one or more elements containing a given attribute value.
For instance, with the same HTML, we can write:
const img = document.querySelector("img[src~='https://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg']");
console.log(img)
We get the img
element with the src
attribute containing https://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg
.
And we can replace querySelector
with querySelectorAll
to get all the img
elements with src
attributes containing the given URL.
Conclusion
We can select elements with the given attribute value with some simple CSS selectors and the querySelector
or querySelectorAll
methods.