Languages
[Edit]
EN

JavaScript - add data attribute to HTML element

6 points
Created by:
lena
714

In this short article, we would like to show how to add data-* attribute to any element using JavaScript.

Quick solution:

element.setAttribute('data-attribute-name', 'attribute-value');

or:

element.dataset.attributeName = 'attribute-value';

// Hint: camelCase naming convention for data-attribute-name

 

Practical examples

1. Using setAttribute() method

data-* attributes are can be added in the same way like normal attributes.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="my-element"></div>
  <script>

    const element = document.querySelector("#my-element");
    
    element.setAttribute('data-attribute-name', 'attribute-value');  // <---------- data attribute adding

    console.log(element.outerHTML);  // <div id="my-element" data-attribute-name="attribute-value"></div>
    
  </script>
</body>
</html>

2. Using dataset property

DOM provides dataset property that gives access to data-* attributes collection. data-* attributes names are converted to pascalCase notation and available in JavaScript API. The attribute add operation can be performed like a typical assigned object property operation.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div id="my-element"></div>
  <script>

    const element = document.querySelector("#my-element");
    
    element.dataset.attributeName = 'attribute-value';  // <---------- data attribute adding

    console.log(element.outerHTML);  // <div id="my-element" data-attribute-name="attribute-value"></div>
    
  </script>
</body>
</html>

See also

  1. JavaScript - remove data attribute 

Alternative titles

  1. JavaScript - set data attribute value
  2. JavaScript - change data attribute value
  3. JavaScript - add element data attribute
  4. JavaScript - set element data attribute value
  5. JavaScript - change element data attribute value
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join