How to Query Elements using Data Attribute in JavaScript
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!
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Getting Started with Sass
- How to Scrape the Web using Node.js and Puppeteer
- Using Push.js to Display Web Browser Notifications
- Setting Up a Local Web Server using Node.js