- Instant help with your JavaScript coding problems

Add data attribute to element in JavaScript

Question:
How to add data attribute to element in JavaScript?
Answer:
element.dataset.id = 123;
Description:

The data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM. 

You can get or set a data attribute through the dataset object in JavaScript like this:

// Reading data-id attribute
const id = myElement.dataset.id;

// Set data-event attribute
myElement.dataset.event = 'ADD';
Share "How to add data attribute to element in JavaScript?"