Problem
What is the most efficient approach to pick all DOM components that have a specific data-attribute (let’s say data-foo) using only pure JavaScript?
Different elements may be used, such as:
<p data-foo="0"></p><br/><h6 data-foo="1"></h6>
Asked by JLeonard
Solution #1
querySelectorAll: can be used.
document.querySelectorAll('[data-foo]');
Answered by Joe
Solution #2
document.querySelectorAll("[data-foo]")
All elements with that attribute will be returned.
document.querySelectorAll("[data-foo='1']")
You’ll only get ones with a value of one.
Answered by Joseph Marikle
Solution #3
document.querySelectorAll('data-foo')
to get a list of all components with the data-foo attribute
If you want to acquire an element with a data attribute that has a specified value, for example,
<div data-foo="1"></div>
<div data-foo="2" ></div>
I’m looking for a div with data-foo set to “2”
document.querySelector('[data-foo="2"]')
But here’s the catch: what if I want to match the data attribute value to the value of a variable? For example, if the data-foo attribute is set to I I want to get element.
var i=2;
Using template literals, you can dynamically select the element with a given data element.
document.querySelector(`[data-foo="${i}"]`)
Note that even if you don’t write the value in a string, it will be converted to one. For example, if I write
<div data-foo=1></div>
When you view the element in Chrome Developer Tools, you’ll see something like this.
<div data-foo="1"></div>
You may also double-check by typing the following code into the terminal.
console.log(typeof document.querySelector(`[data-foo]="${i}"`).dataset('dataFoo'))
Because dataset properties are converted to camelCase properties, I’ve written ‘dataFoo’ even though the property is data-foo.
I’ve included some links below.
https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/data-* https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
This is my first stackoverflow response; please tell me how I can improve my answer writing style.
Answered by Ankit Tiwari
Solution #4
Click here to try it out.
<!DOCTYPE html>
<html>
<head></head>
<body>
<p data-foo="0"></p>
<h6 data-foo="1"></h6>
<script>
var a = document.querySelectorAll('[data-foo]');
for (var i in a) if (a.hasOwnProperty(i)) {
alert(a[i].getAttribute('data-foo'));
}
</script>
</body>
</html>
Answered by shawndumas
Solution #5
Here’s one that’s worth considering: It adds a dummy property to elements matching the selector using the browser’s CSS engine, and then evaluates the calculated style to discover matched elements:
Answered by Heinrich Ulbricht
Post is based on https://stackoverflow.com/questions/7084557/select-all-elements-with-a-data-xxx-attribute-without-using-jquery