Remove all attributes

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

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


to



        
9条回答
  •  情深已故
    2020-11-27 04:50

    Update: the previous method works in IE8 but not in IE8 compatibility mode and previous versions of IE. So here is a version that does and uses jQuery to remove the attributes as it does a better job of it:

    $("img").each(function() {
      // first copy the attributes to remove
      // if we don't do this it causes problems
      // iterating over the array we're removing
      // elements from
      var attributes = $.map(this.attributes, function(item) {
        return item.name;
      });
    
      // now use jQuery to remove the attributes
      var img = $(this);
      $.each(attributes, function(i, item) {
        img.removeAttr(item);
      });
    });
    

    Of course you could make a plug-in out of it:

    jQuery.fn.removeAttributes = function() {
      return this.each(function() {
        var attributes = $.map(this.attributes, function(item) {
          return item.name;
        });
        var img = $(this);
        $.each(attributes, function(i, item) {
        img.removeAttr(item);
        });
      });
    }
    

    and then do:

    $("img").removeAttributes();
    

提交回复
热议问题