Eli Grey

HTML 5 dataset support

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.'
  • Rob Lemon

    demo is broken boss – 404

  • Matt

    I’m getting errors in IE 7-9, which is the only reason anyone even needs this polyfill. ‘Element is undefined’, and ‘Unable to set value’, and ‘Object doesn’t support __lookupGetter__’. 
    Any ideas?

    • Mihai

      same here, anyone?

  • Pingback: HTML5 Cross Browser Polyfills()

  • Brett

    If your purpose is encouraging standards, why not a BSD-type license so any code can use it?

  • Pingback: ¿QUE ES HTML5? « rosaa666()

  • Pingback: html5 « enbolivia.com srl.()

  • Pingback: Sebaduran - Blog()

  • Sham

    Line 20 of your code doesn’t seem to work in any browser, even browsers with dataset support, and will always return ‘undefined’. And the lookupGetter function doesn’t work in IE 10 (still a scumbag browser) – all those aside, nice code though, lamdas / closures are funny little things.

  • Pingback: Las 15 APIs más populares de HTML5 | cMex()