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)?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- Keeping track of variable instances
element.attributes
will give you aNamedNodeList
with all attributes of the element.Just check the attribute names if they start with
data-
Example
If you are using jQuery, you can access data-* attributes through $.data() method: http://api.jquery.com/data/
I needed this but also needed access to the keys, so I wrote a function based on the solution given by Andreas:
And to use it, instead of doing
element.dataset
, you doelement.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 likedataset_simulated(elem)
:You could also try the following method: