We can use data-
attributes to store data in our HTML elements.
Therefore, we may want to get these elements and use them.
In this article, we’ll look at how to select all elements with a data-
attribute with vanilla JavaScript.
Select All Elements with a “data-*” Attribute With Vanilla JavaScript
We can select all elements with a data-
attribute with the document.querySelectorAll
method.
For instance, we can write the following HTML:
<p data-foo='1'>
1
</p>
<p data-foo='2'>
2
</p>
Then we can select all the elements with the data-foo
attribute by writing:
const dataFoo = document.querySelectorAll('[data-foo]');
console.log(dataFoo)
To select the elements with the data-foo
attribute set to a given value, we can write:
const dataFoo = document.querySelectorAll('[data-foo="1"]');
console.log(dataFoo)
Then we get the data-foo
attribute with the value set to 1.
To get the value attribute value from the element object, we can use the dataset
property.
For instance, we can write:
const dataFoo = document.querySelector('[data-foo="1"]');
console.log(dataFoo.dataset.foo)
to select the element with the data-foo
attribute set to 1 with document.querySelector
.
Then we use dataFoo.dataset.foo
to get the value of the data-foo
attribute from the selected element.
The dataFoo.dataset.foo
property is also a setter, so we can write:
const dataFoo = document.querySelector('[data-foo="1"]');
dataFoo.dataset.foo = 3
to replace the data-foo
attribute value of 1 with 3.
Conclusion
We can select all elements with the given data-
attribute set with the document.querySelectorAll
method with the given selector.