How to Get and Set Data Attributes using JavaScript
Table of Contents
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:
HTML<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:
JAVASCRIPTconst city = document.querySelector(".city");
Now we can use the dataset
property to access the data attribute:
JAVASCRIPTconst city = document.querySelector(".city");
const country = city.dataset.country;
console.log(country);
BASHfrance
Alternatively, you can use the getAttribute
method to access the data attribute:
JAVASCRIPTconst city = document.querySelector(".city");
const country = city.getAttribute("data-country");
console.log(country);
BASHfrance
How to set data attributes
Setting a data attribute is also straightforward.
Simply set the value of the data attribute on the dataset
property.
JAVASCRIPTconst city = document.querySelector(".city");
city.dataset.country = "germany";
console.log(city.dataset.country);
BASHgermany
Alternatively, you can use the setAttribute
method to set the data attribute:
JAVASCRIPTconst city = document.querySelector(".city");
city.setAttribute("data-country", "germany");
console.log(city.dataset.country);
BASHgermany
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!
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Create an RSS Reader in Node
- Getting Started with Electron
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Setting Up Stylus CSS Preprocessor