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
- Managing PHP Dependencies with Composer
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy a MySQL Server using Docker
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Creating a Twitter bot with Node.js
- Getting Started with Vuex: Managing State in Vue
- Getting Started with Moon.js