Skip to content

Instantly share code, notes, and snippets.

@nanna-dk
Forked from salcode/gist:6912619
Created August 23, 2016 18:32
Show Gist options
  • Select an option

  • Save nanna-dk/6155e15dcf736414f88b37e96890ac59 to your computer and use it in GitHub Desktop.

Select an option

Save nanna-dk/6155e15dcf736414f88b37e96890ac59 to your computer and use it in GitHub Desktop.
jQuery function to remove all "data-" attributes from a given element
// removes all data attributes from a target element
// example: removeDataAttributes('#user-list');
function removeDataAttributes(target) {
var i,
$target = $(target),
attrName,
dataAttrsToDelete = [],
dataAttrs = $target.get(0).attributes,
dataAttrsLen = dataAttrs.length;
// loop through attributes and make a list of those
// that begin with 'data-'
for (i=0; i<dataAttrsLen; i++) {
if ( 'data-' === dataAttrs[i].name.substring(0,5) ) {
// Why don't you just delete the attributes here?
// Deleting an attribute changes the indices of the
// others wreaking havoc on the loop we are inside
// b/c dataAttrs is a NamedNodeMap (not an array or obj)
dataAttrsToDelete.push(dataAttrs[i].name);
}
}
// delete each of the attributes we found above
// i.e. those that start with "data-"
$.each( dataAttrsToDelete, function( index, attrName ) {
$target.removeAttr( attrName );
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment