Skip to content

Instantly share code, notes, and snippets.

@salcode
Last active November 8, 2023 01:11
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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);
});
};
@adroitcode
Copy link

nice

@simongcc
Copy link

thanks

@esjosemartinez
Copy link

Thanks!

@mellis3
Copy link

mellis3 commented Sep 1, 2016

Nice, this works great. Thanks for sharing and all the comments

@yairEO
Copy link

yairEO commented Apr 25, 2017

why do you even need jQuery here....

@seemabkhalil95
Copy link

nice

@laurentmuller
Copy link

All in one function:

$.each($target.data(), function (key) {
    $target.removeAttr('data-' + key);
});

@salcode
Copy link
Author

salcode commented May 29, 2019

@laurentmuller this is really cool. I wanted to test that your shorter version works so I could update this gist.

I created two codepens.

Unfortunately, I found an edge case with data-eighty-eight="88".

The problem appears to be that $target.data() gives us the attributes in camelCase. This isn't a problem for single words (e.g. data-one="1" has a key of one), however when you have multiple dashes, the camelCase gives us the "wrong" key (e.g. data-eighty-eight="88" has a key of eightyEight, when we need a key of eighty-eight).

If we add something to convert the key from camelCase to kabob-case, I think we'll be in business.

@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