-
-
Save nanna-dk/6155e15dcf736414f88b37e96890ac59 to your computer and use it in GitHub Desktop.
jQuery function to remove all "data-" attributes from a given element
This file contains hidden or 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
| // 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