Skip to content

Instantly share code, notes, and snippets.

@sunpig
Created August 2, 2012 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunpig/3236740 to your computer and use it in GitHub Desktop.
Save sunpig/3236740 to your computer and use it in GitHub Desktop.
JS implementation of [DOMElement].dataset property
/**
* Not all browsers support the .dataset property
* for DOM elements. This function performs the same
* function: it gathers all the data-* attributes of a
* DOM element, and returns them as a hash.
* Example: <p id="testP" data-monkey="fez" data-turtle="mine"></p>
* getDataset(p); // {'monkey':'fez', 'turtle':'mine'}
*/
function getDataset(el) {
var dataset = {};
var attributes, attribute, attributeName, i;
if (el && el.nodeType==1 /* DOMElement */) {
attributes = el.attributes;
if (attributes && attributes.length) {
i = attributes.length;
while (i--) {
attribute = attributes.item(i);
attributeName = attribute.nodeName;
if (attributeName.slice(0,5) === 'data-') {
dataset[attributeName.slice(5)] = attribute.value;
}
}
}
}
return dataset;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment