Skip to content

Instantly share code, notes, and snippets.

@glebofff
Created October 10, 2015 17:15
Show Gist options
  • Save glebofff/0d54a4ed20a33b5113f7 to your computer and use it in GitHub Desktop.
Save glebofff/0d54a4ed20a33b5113f7 to your computer and use it in GitHub Desktop.
.dataset shim (works in IE9)
// Begin dataset code
if (!document.documentElement.dataset &&
// FF is empty while IE gives empty object
(!Object.getOwnPropertyDescriptor(Element.prototype, 'dataset') ||
!Object.getOwnPropertyDescriptor(Element.prototype, 'dataset').get)
) {
var propDescriptor = {
get: function () {
'use strict';
var i,
HTML5_DOMStringMap = {},
attrVal, attrName, propName,
attribute,
attributes = this.attributes,
attsLength = attributes.length,
toUpperCase = function (n0) {
return n0.charAt(1).toUpperCase();
},
getter = function () {
return this;
},
setter = function (attrName, value) {
return (typeof value !== 'undefined') ? this.setAttribute(attrName, value) : this.removeAttribute(attrName);
};
for (i = 0; i < attsLength; i++) {
attribute = attributes[i];
// Fix: This test really should allow any XML Name without
// colons (and non-uppercase for XHTML)
if (attribute && attribute.name &&
(/^data-\w[\w\-]*$/).test(attribute.name)) {
attrVal = attribute.value;
attrName = attribute.name;
// Change to CamelCase
propName = attrName.substr(5).replace(/-./g, toUpperCase);
HTML5_DOMStringMap[propName] = attrVal;
}
}
return HTML5_DOMStringMap;
}
};
Object.defineProperty(Element.prototype, 'dataset', propDescriptor);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment