Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to get data attribute value in JavaScript

Understanding Data Attributes

In the realm of web development, data attributes in HTML play a pivotal role. They allow us to store extra information in standard HTML elements without resorting to non-standard attributes, extra properties on DOM, or Node.setUserData(). In simpler terms, think of them as a way to add some extra details about an HTML element, like adding a note to a recipe about possible substitutions or additions.

To define these data attributes, we use data- followed by whatever name you choose. For example:

<div id="myDiv" data-myAttribute="myValue">Hello, World!</div>

In this example, myAttribute is a data attribute for the div element, and it has a value of myValue.

Accessing Data Attributes in JavaScript

Now that we have some extra information stored in our HTML, how do we access it in JavaScript? There are two main ways, and we'll dive into each one.

Using the dataset property

The first method is by utilizing the dataset property. This property provides read/write access to all the custom data attributes (data-*) set on the element. It's like opening a special drawer filled with extra details about the element.

Let's use our earlier div example. To access the myAttribute data attribute, we can do the following:

let div = document.getElementById('myDiv');
let value = div.dataset.myAttribute;
console.log(value); // "myValue"

In the code above, document.getElementById('myDiv') is used to grab the div element with the id 'myDiv'. div.dataset.myAttribute then retrieves the value of data-myAttribute. The dataset property automatically converts the kebab-case (words separated by dashes) attribute name to camelCase.

Using the getAttribute() function

The second method involves the getAttribute() function. This function returns the value of a specified attribute on the element. Think of it as asking the element about a specific detail directly.

Here's how you can use it:

let div = document.getElementById('myDiv');
let value = div.getAttribute('data-myAttribute');
console.log(value); // "myValue"

In the example above, div.getAttribute('data-myAttribute') is used to directly access the data-myAttribute attribute and retrieve its value.

Choosing Between dataset and getAttribute()

So, which method should you use? The dataset property or the getAttribute() function? The answer depends on the situation. The dataset property is a convenient way to access all data attributes, but it only works with strings. If you plan to work with boolean values, integers, or any data type that isn't a string, getAttribute() might be a better option as it will always return the exact value of the attribute.

Modifying Data Attributes

Data attributes are not just for reading; we can also modify their values. For instance, if we're working with a game and want to update the score stored in a data attribute, we can do so using the dataset property or setAttribute() function.

Here's how to do it with dataset:

let div = document.getElementById('myDiv');
div.dataset.myAttribute = 'new value';
console.log(div.dataset.myAttribute); // "new value"

And here's how to do it with setAttribute():

let div = document.getElementById('myDiv');
div.setAttribute('data-myAttribute', 'new value');
console.log(div.getAttribute('data-myAttribute')); // "new value"

Conclusion: The Power of Data Attributes

By now, you should have a good understanding of how to get and set data attribute values in JavaScript. But why does this matter? Because data attributes give you the power to store and manipulate extra information directly within your HTML elements. They're like hidden pockets in a jacket, holding keys that can unlock more interactive, more dynamic user experiences. Whether it's storing a user's score in a game, tracking custom analytics, or managing states in a complex application, data attributes are there, ready to be leveraged. So, the next time you find yourself needing to stash away some data in your HTML, remember the humble data attribute and the power it holds.