There are two ways in which you can remove a data-*
attribute from an HTML element:
Using the delete
Operator on dataset
Property
Custom data-*
attributes are accessible via the dataset
property, where the attributes are accessible without the data-
prefix, in camel case (instead of dashes). For example, data-key-name
is accessible via element.dataset.keyName
in JavaScript.
Therefore, to remove a custom data
attribute property from the dataset
property, you can use the delete
operator, for example, like so:
<div id="foo" data-total-count="123">foobar</div>
const foo = document.getElementById('foo'); console.log(foo.dataset.totalCount); // '123' delete foo.dataset.totalCount; console.log(foo.dataset.totalCount); // undefined
Using Element.removeAttribute()
You can use the Element.removeAttribute()
to remove any attribute on an HTML element, including data-*
attributes, for example, like so:
<div id="foo" data-total-count="123">foobar</div>
const foo = document.getElementById('foo'); console.log(foo.dataset.totalCount); // '123' foo.removeAttribute('data-total-count'); console.log(foo.dataset.totalCount); // undefined
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.