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!
- Getting Started with TypeScript
- Getting Started with Solid
- Getting Started with Svelte
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to deploy a PHP app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Learn how to build a Slack Bot using Node.js
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up a Local Web Server using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript