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