EN
JavaScript - add data attribute to HTML element
6 points
In this short article, we would like to show how to add data-*
attribute to any element using JavaScript.
Quick solution:
xxxxxxxxxx
1
element.setAttribute('data-attribute-name', 'attribute-value');
or:
xxxxxxxxxx
1
element.dataset.attributeName = 'attribute-value';
2
3
// Hint: camelCase naming convention for data-attribute-name
data-*
attributes are can be added in the same way like normal attributes.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="my-element"></div>
5
<script>
6
7
const element = document.querySelector("#my-element");
8
9
element.setAttribute('data-attribute-name', 'attribute-value'); // <---------- data attribute adding
10
11
console.log(element.outerHTML); // <div id="my-element" data-attribute-name="attribute-value"></div>
12
13
</script>
14
</body>
15
</html>
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.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="my-element"></div>
5
<script>
6
7
const element = document.querySelector("#my-element");
8
9
element.dataset.attributeName = 'attribute-value'; // <---------- data attribute adding
10
11
console.log(element.outerHTML); // <div id="my-element" data-attribute-name="attribute-value"></div>
12
13
</script>
14
</body>
15
</html>