admin管理员组文章数量:1290978
I need a way to list the data-*
attributes of an element. I would use Object.keys(element.dataset)
but IE 9.0 doesn't have dataset
support. How should I do this in a way that works for IE 9.0 (and Chrome, Firefox, Safari)?
I need a way to list the data-*
attributes of an element. I would use Object.keys(element.dataset)
but IE 9.0 doesn't have dataset
support. How should I do this in a way that works for IE 9.0 (and Chrome, Firefox, Safari)?
4 Answers
Reset to default 6element.attributes
will give you a NamedNodeList
with all attributes of the element.
Just check the attribute names if they start with data-
var attributes = element.attributes,
i = attributes.length;
for (; i--; ){
if (/^data-.*/.test(attributes[i].name)) {
console.log(attributes[i].name);
}
}
Example
If you are using jQuery, you can access data-* attributes through $.data() method: http://api.jquery./data/
I needed this but also needed access to the keys, so I wrote a function based on the solution given by Andreas:
Element.prototype.dataset_simulated = function(){
var attributes = this.attributes;
var simulatedDataset = {};
for (var i = attributes.length; i--; ){
if (/^data-.*/.test(attributes[i].name)) {
var key = attributes[i].name.replace('data-', '');
var value = this.getAttribute(attributes[i].name);
simulatedDataset[key] = value;
}
}
return simulatedDataset;
};
And to use it, instead of doing element.dataset
, you do element.dataset_simulated()
.
and here's the fiddle
Edit:
It appears that IE<8 also has no support for Element.prototype
, so this can simply be a function with usage like dataset_simulated(elem)
:
function dataset_simulated(elem){
var attributes = elem.attributes;
var simulatedDataset = {};
for (var i = attributes.length; i--; ){
if (/^data-.*/.test(attributes[i].name)) {
var key = attributes[i].name.replace('data-', '');
var value = elem.getAttribute(attributes[i].name);
simulatedDataset[key] = value;
}
}
return simulatedDataset;
};
You could also try the following method:
[dom_element].getAttribute('[your data-* attribute name]');
本文标签: javascriptelementdataset in Internet ExplorerStack Overflow
版权声明:本文标题:javascript - element.dataset in Internet Explorer - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741522354a2383263.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论