Thought leadership from the most innovative tech companies, all in one place.

How to Get and Set the Value of a Data Attribute with JavaScript

How to get and set the value of the `data-id` attribute of an element with JavaScript.

Photo by Luke Chesseron Unsplash

Photo by Luke Chesser on Unsplash

With data- attributes, we can store data that we want to store within our HTML elements.

We may want to get these values in our web app.

And we can use JavaScript to do this.

In this article, we’ll look at how to get and set the value of the data-id attribute of an element with JavaScript.

The getAttribute Method

One way to get the value of an attribute is to use the getAttribute method available natively.

For instance, if we have the following HTML:

<div id='apple-tree' data-fruit='12'></div>

We can call getAttribute to return the value of the data-fruit attribute by writing;

const plant = document.getElementById('apple-tree');
const fruitCount = plant.getAttribute('data-fruit');

fruitCount should be '12' since this is the value of the data-fruit attribute.

And to change the value of the data-fruit attribute, we can write:

plant.setAttribute('data-fruit','10');

Use the dataset Property

HTML element node objects come with the dataset property to let us get the values of attributes that start with the data- prefix.

For instance, we can write:

const plant = document.getElementById('apple-tree');
console.log(plant.dataset.fruit)

To get the value of the data-fruit attribute, we use the plant.dataset.fruit property.

The property can also be assigned a value, so we can set the value of the data-fruit attribute by writing:

plant.dataset.fruit = 10

jQuery

jQuery lets us get a value of an attribute that starts with data- with various ways.

One way to get the value is to use the data method.

For instance, we can write:

console.log($('#apple-tree').data().fruit)

to get the value of the data-fruit property.

data returns an object all the data- attributes property names that has the data- prefix removed.

And the corresponding value is the value of the attributes added to the element.

Also, we can write:

console.log($('#apple-tree').data('fruit'))

to do the same thing.

Conclusion

We can store data in elements by using data- attributes.

And we can get and set their values with plain JavaScript or jQuery.




Continue Learning