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); | |
}); | |
}; |
@laurentmuller nice! I agree this version does the same work with many fewer lines of code.
I've updated this gist with your new shorter version. Thanks!
You don't need the regular expression
for (let key in element.dataset)
delete element.dataset[key];
When you delete a dataset element, the attribute is removed automatically
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ok, You are right. So a new implementation: