Last active
November 8, 2023 01:11
-
-
Save salcode/6912619 to your computer and use it in GitHub Desktop.
jQuery function to remove all "data-" attributes from a given element
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
// Note: This is an improved version provided by @laurentmuller in the comments below. | |
// removes all data attributes from a target element | |
// example: removeDataAttributes('#user-list'); | |
function removeDataAttributes(target) { | |
var $target = $(target); | |
// Loop through data attributes. | |
$.each($target.data(), function (key) { | |
// Because each key is in camelCase, | |
// we need to convert it to kabob-case and store it in attr. | |
var attr = 'data-' + key.replace(/([A-Z])/g, '-$1').toLowerCase(); | |
// Remove the attribute. | |
$target.removeAttr(attr); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You don't need the regular expression
When you delete a dataset element, the attribute is removed automatically