Skip to content

Instantly share code, notes, and snippets.

@benjasHu
Created September 27, 2015 16:43
Show Gist options
  • Save benjasHu/7d7be253ef1ca434b708 to your computer and use it in GitHub Desktop.
Save benjasHu/7d7be253ef1ca434b708 to your computer and use it in GitHub Desktop.
Extract element data attributes and return as an object [ES6]
/**
* Extract only data attributes from an element (or a jQuery element) and return it as an object
* @param {Element} el JS raw element or jQuery element
* @param {String} dataTag data key from extract the rest. Could start with "data-" or not
* @param {Boolean} camelCase keys returned camelCased or not
* @return {Object}
*
* IMPORTANT: It use lodash/underscore as a dependency!
* IMPORTANT: Made in ES6
*
* Ex: <p data-foo-theme="main" data-foo-hide="false" data-foo-timeout="500"></p>
*
* Will return:
* {
* fooTheme: 'main',
* fooHide: false,
* fooTimeout: 500
* }
*
*/
function getDatas( el, dataTag='', camelCase=true ) {
if(!el) throw new Error('Element is undefined');
let datas = _.isElement(el) ? el.attributes : el[0].attributes,
options = {};
if(!datas || !datas.length) return {};
_.each(datas, (value, key) => {
let nodeName = value.nodeName,
nodeValue = value.nodeValue,
dataSelector = nodeName.indexOf('data-') === -1 ? `data-${dataTag}` : dataTag;
// parse to boolean: true
if(nodeValue === 'true') nodeValue = !!nodeValue;
// parse to boolean: false
if(nodeValue === 'false') nodeValue = !nodeValue;
// parse to number
if(!_.isArray( nodeValue ) && (nodeValue - parseFloat( nodeValue ) + 1) >= 0)
nodeValue = parseInt(nodeValue, 10);
// create data object
if(nodeName.indexOf(dataSelector) !== -1) {
let prop = nodeName.split(dataSelector)[1],
camelCased = camelCase ? _.camelCase(prop) : prop;
options[camelCased] = nodeValue;
}
});
return options;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment