Using only pure JavaScript, what is the most efficient way to select all DOM elements that have a certain data-
attribute (let's say data-foo
).
The elements may be different, for example:
<p data-foo="0"></p><br/><h6 data-foo="1"></h6>
To get all DOM elements by a data attribute, use the querySelectorAll method, e.g. document. querySelectorAll('[data-id]') . The querySelectorAll method returns a NodeList containing the elements that match the specified selector.
The * selector selects all elements. The * selector can also select all elements inside another element (See "More Examples").
We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.
The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".
You can use querySelectorAll:
document.querySelectorAll('[data-foo]');
document.querySelectorAll("[data-foo]")
will get you all elements with that attribute.
document.querySelectorAll("[data-foo='1']")
will only get you ones with a value of 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With