I am trying to find a way to remove from a page all matching data attributes from different kind of elements.
I now loop an array, but the list of names is to long therefor I hope there's a better way to remove my custom data attributes.....with a regex pattern?
// the code
var dataArr = ['data-myplugin-value',
'data-myplugin-id',
...
...
...
...
'data-myplugin-name'];
$.each(dataArr, function(i,a){
$('['+a+']').removeAttr(a);
});
To remove all attributes of elements, we use removeAttributeNode() method.
Make use of the removeAttribute() method to delete the given data attribute: el. removeAttribute('data-foo'); Apart from setting, getting, and erasing data values, all three methods are also used for manipulating other element attributes.
removeAttr( attributeName )Returns: jQuery. Description: Remove an attribute from each element in the set of matched elements.
To prevent this, use . removeAttr() alongside . removeData() to remove the data- attribute as well.
If you don't mind using XPath, here is my solution:
function removeMyDataAttributes() {
var list, iterator, attribute, i, n;
// Select all attribute nodes that it's name starts with "data-myplugin-"
iterator = document.evaluate('//*/attribute::*[starts-with(local-name(), "data-myplugin-")]',
document.documentElement, null, XPathResult.ANY_TYPE, null);
list = [];
while ((attribute = iterator.iterateNext())) {
list.push(attribute);
// Note: can't call removeAttributeNode here:
// InvalidStateError: Failed to execute 'iterateNext' on 'XPathResult': The document has mutated since the result was returned.
}
for (i = 0, n = list.length; i < n; ++i) {
attribute = list[ i ];
attribute.ownerElement.removeAttributeNode(attribute);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With