Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selected and remove all matching data attributes

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);  
});
like image 937
user759235 Avatar asked May 25 '14 00:05

user759235


People also ask

How do I remove all attributes from an element?

To remove all attributes of elements, we use removeAttributeNode() method.

How do I delete data attributes?

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.

Which jQuery method is used to remove attribute from all the matched elements?

removeAttr( attributeName )Returns: jQuery. Description: Remove an attribute from each element in the set of matched elements.

How remove data attribute value in jQuery?

To prevent this, use . removeAttr() alongside . removeData() to remove the data- attribute as well.


1 Answers

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);
    }
}
like image 84
amobiz Avatar answered Nov 07 '22 20:11

amobiz