Table of Contents
Sometimes it is useful to be able to query for elements in the DOM using their data attributes.
Data attributes are a way to associate data with elements in the DOM. Any attribute that starts with a data-
prefix is considered a data attribute.
In this post, we will learn how to query for elements using their data attributes.
Querying for Elements Using Data Attributes
For our example, let's assume this is our DOM:
HTML<div data-id="1" data-name="foo">Foo</div>
<div data-id="2" data-name="bar">Bar</div>
<div data-id="3" data-name="baz">Baz</div>
Querying a Single Element
Let's start with the simplest query, getting a single element. We'll be using docuemnt.querySelector()
to do this.
Simply pass in the data attribute name and value as arguments to document.querySelector()
and you will get the element:
JAVASCRIPTconst foo = document.querySelector('[data-name="foo"]');
console.log(foo);
Querying Multiple Elements
You can go from querying a single element to querying multiple elements.
To do this, we will be using document.querySelectorAll()
instead of document.querySelector()
.
Let's try querying all elements with the data-name
attribute:
JAVASCRIPTconst names = document.querySelectorAll("[data-name]");
console.log(names);
Notice that we get an array of elements back. This means we can loop through the array to get each element.
Here's how we can use the forEach()
method to loop through the array:
JAVASCRIPTnames.forEach(name => console.log(name));
You can also use a normal for
loop to get all the elements one-by-one:
JAVASCRIPTfor (const name of names) {
console.log(name);
}
Conclusion
In this post, we learned how to query for elements using their data attributes.
We can either get single elements using document.querySelector()
or multiple elements using document.querySelectorAll()
.
Hopefully, this has been useful to you. Happy coding!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- Getting Started with Express
- Create an RSS Reader in Node
- Best Visual Studio Code Extensions for 2022
- How to deploy a MySQL Server using Docker
- Getting Started with Sass
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue