-
-
Save salcode/6912619 to your computer and use it in GitHub Desktop.
// 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); | |
}); | |
}; |
nice
All in one function:
$.each($target.data(), function (key) {
$target.removeAttr('data-' + key);
});
@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.
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);
});
@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
why do you even need jQuery here....