How to remove data-* attributes using HTML5 dataset

瘦欲@ 提交于 2019-12-05 08:28:15

问题


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.


回答1:


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>



回答2:


This is to remove all the data-* attributes. You can add a condition in the for loop to remove only particular data-attribute. Hope this helps :)

var elem = document.querySelector('#example');
var dataset = elem.dataset;
for (var key in dataset) {
    elem.removeAttribute("data-" + key.split(/(?=[A-Z])/).join("-").toLowerCase());
}



回答3:


<div data-id="test">test</div>

$(document).ready(function(){
  $("div").removeAttr("data-id"); // removing the data attributes.
  console.log($("div").data("id")); // displays in the console.
});


来源:https://stackoverflow.com/questions/9200712/how-to-remove-data-attributes-using-html5-dataset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!