Remove multiple html5 data-attributes with jquery
In my jQuery placeholder plugin, I’m using the following to get all the attributes for a given element:
function args(elem) {
// Return an object of element attributes
var newAttrs = {},
rinlinejQuery = /^jQuery\d+$/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && !rinlinejQuery.test(attr.name)) {
newAttrs[attr.name] = attr.value;
}
});
return newAttrs;
}
Note that elem
is an element object, not a jQuery object.
You could easily tweak this, to get only data-*
attribute names:
function getDataAttributeNames(elem) {
var names = [],
rDataAttr = /^data-/;
$.each(elem.attributes, function(i, attr) {
if (attr.specified && rDataAttr.test(attr.name)) {
names.push(attr.name);
}
});
return names;
}
You could then loop over the resulting array, and call removeAttr()
for each item on the element.
Here’s a simple jQuery plugin that should do the trick:
$.fn.removeAttrs = function(regex) {
return this.each(function() {
var $this = $(this),
names = [];
$.each(this.attributes, function(i, attr) {
if (attr.specified && regex.test(attr.name)) {
$this.removeAttr(attr.name);
}
});
});
};
// remove all data-* attributes
$('#my-element').removeAttrs(/^data-/);
// remove all data-lorem* attributes
$('#my-element').removeAttrs(/^data-lorem/);
// Fetch an array of all the data
var data = $("a").data(),
i;
// Fetch all the key-names
var keys = $.map(data , function(value, key) { return key; });
// Loop through the keys, remove the attribute if the key contains "lorem".
for(i = 0; i < keys.length; i++) {
if (keys[i].indexOf('lorem') != -1) {
$("a").removeAttr("data-" + keys[i]);
}
}
Fiddle here: http://jsfiddle.net/Gpqh5/
Vanilla JS below clears all data attributes. If you want to add some if
logic to remove a subset of data attributes, it should be trivial to add that functionality to the below JavaScript.
function clearDataAttributes(el){
if (el.hasAttributes()) {
var attrs = el.attributes;
var thisAttributeString = "";
for(var i = attrs.length - 1; i >= 0; i--) {
thisAttributeString = attrs[i].name + "-" + attrs[i].value;
el.removeAttribute(thisAttributeString);
}
}
}