Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove data-* attributes using HTML5 dataset

According to the dataset spec, how is element.dataset meant to delete data attributes? Consider:

<p id="example" data-a="string a" data-b="string b"></p> 

If you do this:

var elem = document.querySelector('#example'); elem.dataset.a = null; elem.dataset.b = undefined; elem.dataset.c = false; elem.dataset.d = 3; elem.dataset.e = [1, 2, 3]; elem.dataset.f = {prop: 'value'}; elem.dataset.g = JSON.stringify({prop: 'value'}); 

the DOM becomes this in Chrome and Firefox:

<p id="example"     data-a="null"     data-b="undefined"     data-c="false"     data-d="3"     data-e="1,2,3"     data.f="[object Object]"     data.g="{"prop":"value"}" ></p> 

The Chrome/Firefox implementation mimics setAttribute. It basically applies .toString() first. This makes sense to me except for the treatment of null because I would expect that null would remove the attribute. Otherwise how does the dataset API do the equivalent of:

elem.removeAttribute('data-a'); 

And what about boolean attributes:

<p data-something> is equivalent to <p data-something=""> Hmm.

like image 449
ryanve Avatar asked Feb 08 '12 20:02

ryanve


People also ask

How do I delete data attributes?

Removing the data attribute const el = document. querySelector(". row"); Now, it has a removeAttribute() property which is used to remove the specified attribute from an element.

How do I remove elements from data attribute Foo?

Make use of the removeAttribute() method to delete the given data attribute: el. removeAttribute('data-foo'); Apart from setting, getting, and erasing data values, all three methods are also used for manipulating other element attributes.

How do I delete a dataset?

To remove a dataset If the panel is not displayed at all, select Datasets from theViewmenu. Right-click the dataset to remove and select Delete From Document.

Can data -* attribute contain HTML tags?

The data-* attribute is a Global Attribute, and can be used on any HTML element.


1 Answers

Wouldn't 'delete' remove dataset element? E.g.:

<div id="a1" data-foo="bar">test</div>  <script> var v = document.getElementById('a1');   alert(v.dataset.foo); delete v.dataset.foo; alert(v.dataset.foo); </script> 
like image 177
maximdim Avatar answered Sep 22 '22 13:09

maximdim