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!
- Getting Started with Express
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a Deno app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Getting Started with Moment.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API