How to Query Elements using Data Attribute in JavaScript

Updated onbyAlan Morel
How to Query Elements using Data Attribute in JavaScript

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:

<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:

const 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:

const 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:

names.forEach(name => console.log(name));

You can also use a normal for loop to get all the elements one-by-one:

for (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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.