Created
August 2, 2012 12:35
-
-
Save sunpig/3236740 to your computer and use it in GitHub Desktop.
JS implementation of [DOMElement].dataset property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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