Skip to content

Instantly share code, notes, and snippets.

@salcode
Last active November 8, 2023 01:11
Show Gist options
  • Save salcode/6912619 to your computer and use it in GitHub Desktop.
Save salcode/6912619 to your computer and use it in GitHub Desktop.
jQuery function to remove all "data-" attributes from a given element
// 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
Copy link

Ok, You are right. So a new implementation:

$.each($target.data(), function (key) {
    var attr = 'data-' + key.replace(/([A-Z])/g, '-$1').toLowerCase(); 
    $target.removeAttr(attr);
});

@salcode
Copy link
Author

salcode commented May 31, 2019

@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!

@imanie383
Copy link

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