How to set data attributes in HTML elements with JavaScript?

Spread the love

Sometimes, we want to set data attributes in HTML elements with JavaScript.

In this article, we’ll look at how to set data attributes in HTML elements with JavaScript.

How to set data attributes in HTML elements with JavaScript?

To set data attributes in HTML elements with JavaScript, we set the dataset property.

For instance, we write

<div id="mydiv" data-myval="10"></div>

to add a div.

Then we write

const myDiv = document.getElementById("mydiv");
const myVal = myDiv.dataset.myval;
mydiv.dataset.myval = "20";
mydiv.dataset.myval = null;

to get the div with getElementById.

Next, we get the data-myval attribute value with

const myVal = myDiv.dataset.myval;

And we its value with

mydiv.dataset.myval = "20";
mydiv.dataset.myval = null;

Conclusion

To set data attributes in HTML elements with JavaScript, we set the dataset property.

Leave a Reply

Your email address will not be published. Required fields are marked *