Update: Getting (not setting) data-* attributes through Element.dataset now works in IE8 with the help of Xccessors.
I have made an implementation of HTML 5 dataset (data-* attributes) support that almost conforms to the HTML 5 spec* and works in Firefox 1.5+, Opera 9.5+, Safari, and Google Chrome. It uses getters and setters to simulate a psuedo-native HTML 5 dataset API. The code is licensed CC GNU LGPL and can be downloaded here. I have uploaded a demo (also in XHTML 5) that you can try out. The script includes these extra functions: Element.removeDataAttribute(name)
, Element.setDataAttribute(name, value)
, and Element.setDataAttributes()
(all explained below).
*You cannot set new items the standard way like Element.dataset.name = value
(already existing items can though). You either have to add new items by doing Element.setDataAttribute(name, value)
for single additions and Element.setDataAttributes(object full of {name, value:String} pairs)
to add multiple items at once. Instead of delete element.dataset[name]
, you must use element.dataset[name] = undefined
or Element.removeDataAttribute(name)
to remove data-name. Example of setting values:
var foo = document.createElement('div'); foo.setDataAttributes({'bar':'blah', 'lorem':'Lorem ipsum.'}); foo.dataset.bar == 'blah'; foo.dataset.bar = 'eligrey.com'; foo.dataset.bar == 'eligrey.com'; foo.setDataAttribute('foobar', foo.dataset.lorem); foo.dataset.foobar == 'Lorem ipsum.' |