Remove multiple html5 data-attributes with jquery

后端 未结 7 1150
清酒与你
清酒与你 2020-12-16 14:25

So jquery api says the following:

Removing data from jQuery\'s internal .data() cache does not effect any HTML5 data- attributes in a document; use .

7条回答
  •  盖世英雄少女心
    2020-12-16 15:04

    I'll post answer as well, as it took me some time to make working version from Mathias post.

    The problems I had was that SVG needs extra-care, there are little nuances(jQuery doesn't like it), but here is the code that should work for SVG as well:

    $.fn.removeAttrs = function(attrToRemove, attrValue) {
        return this.each(function() {
            var $this = $(this)[0];
            var toBeRemoved = [];
            _.each($this.attributes, function (attr) {
                if (attr && attr.name.indexOf(attrToRemove) >= 0) {
                    if (attrValue && attr.value !== attrValue)
                        return;
    
                    toBeRemoved.push(attr.name);
                }
            });
    
            _.each(toBeRemoved, function(attrName) {
                $this.removeAttribute(attrName);
            });
        });
    };
    

    note that it is using underscore, but you could replace _.each with $.each I believe.

    Usage:

    svgMapClone
        .find('*')
        .addBack()
        .removeAttrs('svg-')
        .removeAttrs('context-')
        .removeAttrs('class', '')
        .removeAttrs('data-target')
        .removeAttrs('dynamic-cursor')
        .removeAttrs('transform', 'matrix(1, 0, 0, 1, 0, 0)')
        .removeAttrs("ng-");
    

提交回复
热议问题