Remove all attributes

后端 未结 9 682
天涯浪人
天涯浪人 2020-11-27 04:01

Is it possible to remove all attributes at once using jQuery?


to



        
9条回答
  •  执念已碎
    2020-11-27 04:46

    Instead of creating a new jQuery.fn.removeAttributes (demonstrated in the accepted answer) you can extend jQuery's existing .removeAttr() method making it accept zero parameters to remove all attributes from each element in a set:

    var removeAttr = jQuery.fn.removeAttr;
    jQuery.fn.removeAttr = function() {
    
      if (!arguments.length) {
        this.each(function() {
    
          // Looping attributes array in reverse direction
          // to avoid skipping items due to the changing length
          // when removing them on every iteration.
          for (var i = this.attributes.length -1; i >= 0 ; i--) {
            jQuery(this).removeAttr(this.attributes[i].name);
          }
        });
    
        return this;
      }
    
      return removeAttr.apply(this, arguments);
    };
    

    Now you can call .removeAttr() without parameters to remove all attributes from the element:

    $('img').removeAttr();
    

提交回复
热议问题