How to remove a HTML data attribute in JavaScript
In this tutorial, we are going to learn how to remove the HTML data attributes using JavaScript.
Consider, we have the following html element with the data attribute data-color="green"
:
<div data-color="green" class="row">First div</div>
Now, we need to remove the above element data attribute in JavaScript.
Removing the data attribute
To remove the data attribute from an html element, first we need to access it inside the JavaScript using the document.querySelector()
method.
const el = document.querySelector(".row");
Now, it has a removeAttribute()
property which is used to remove the specified attribute from an element.
el.removeAttribute("data-color");
We can also remove the multiple data attributes from a html element like this:
const el = document.querySelector(".row");
Object.keys(el.dataset).forEach(key=>{
delete el.dataset[key];
})