Skip to content

Instantly share code, notes, and snippets.

@dented
Last active September 15, 2015 03:22
Show Gist options
  • Save dented/87a3703d2bd978c8d2dc to your computer and use it in GitHub Desktop.
Save dented/87a3703d2bd978c8d2dc to your computer and use it in GitHub Desktop.
Retrieve Groups of prefixed data attributes (data-options-id, data-options-name, etc)
function camelize(str) {
return str.replace(/(?:^\w|[A-Z]|\b\w)/g, function (letter, index) {
return index == 0 ? letter.toLowerCase() : letter.toUpperCase();
}).replace(/\s+/g, '');
}
$.fn.extend({
dataGrouping: function (attributeName) {
var regExp = new RegExp('^' + attributeName),
attributesFound = {};
this.each(function (idx, element) {
var i,
attributes = element.dataset,
attributesLength = element.dataset.length;
for (var attr in attributes) {
if (regExp.test(attr)) {
var key = camelize(attr.replace(attributeName, ''));
attributesFound[key] = attributes[attr];
}
}
});
return attributesFound;
}
});
// var additionalData = $('.items:first').dataGrouping('additional');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment