How to Get and Set Data Attributes using JavaScript

Updated onbyAlan Morel
How to Get and Set Data Attributes using JavaScript

HTML allows for special attributes on elements called data attributes.

These attributes are used to store extra information on a tag which you can manipulate with JavaScript.

In this post, we'll learn how to use data attributes, how to access them, and how to set them using JavaScript.

How to use data attributes

Using data attributes is straightforward.

You simply add a data attribute to an element by prefixing the attribute name with data-.

For example, here is a simple div with a data attribute:

<div data-country="france" class="city">
    Paris
</div>

Here, we have a div with a data attribute called data-country with a value of france, wrapped around the text Paris.

Now, let's see how we could access this data attribute using JavaScript.

How to access data attributes

To access a data attribute, we can use the dataset property on the element.

First, let's query for this element:

const city = document.querySelector(".city");

Now we can use the dataset property to access the data attribute:

const city = document.querySelector(".city");

const country = city.dataset.country;

console.log(country);
france

Alternatively, you can use the getAttribute method to access the data attribute:

const city = document.querySelector(".city");

const country = city.getAttribute("data-country");

console.log(country);
france

How to set data attributes

Setting a data attribute is also straightforward.

Simply set the value of the data attribute on the dataset property.

const city = document.querySelector(".city");

city.dataset.country = "germany";

console.log(city.dataset.country);
germany

Alternatively, you can use the setAttribute method to set the data attribute:

const city = document.querySelector(".city");

city.setAttribute("data-country", "germany");

console.log(city.dataset.country);
germany

Conclusion

In this post, we learned how to use data attributes, how to access them, and how to set them using JavaScript.

Simply prefix the attribute name with data- and you can use it to store extra information on an element, then access it using the dataset property or the getAttribute method.

Thanks for reading!

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.