10

how to remove all attributes from with js or jquery. (I don't know what is the attributes in the body, i want remove all them)

Yi Jiang
  • 48,053
  • 16
  • 135
  • 134
faressoft
  • 18,165
  • 42
  • 99
  • 142

5 Answers5

21

You can use the DOM Level 1 Core attributes property to access attributes as a list. As plain JS:

function removeAllAttrs(element) {
    for (var i= element.attributes.length; i-->0;)
        element.removeAttributeNode(element.attributes[i]);
}
removeAllAttrs(document.body);

Or dressed up in jQuery plugin clothes:

$.fn.removeAllAttrs= function() {
    return this.each(function() {
        $.each(this.attributes, function() {
            this.ownerElement.removeAttributeNode(this);
        });
    });
};

$('body').removeAllAttrs();
bobince
  • 514,530
  • 102
  • 640
  • 820
  • This is what i need.Thank you very much. – faressoft Aug 29 '10 at 02:02
  • Does this work in IE? In IE `attributes` contains all possible attribute names, regardless of whether they've been set, and I wondered if that could cause problems. Haven't tested it yet. – Tim Down Aug 29 '10 at 12:39
  • Array-like access to `attributes` does seem to work, independently of the issues with property-name access. – bobince Aug 29 '10 at 15:41
  • Instead of creating a new `$.fn.removeAllAttrs` you can extend jQuery's existing `.removeAttr()` method making it accept zero parameters to remove all attributes from each element: http://stackoverflow.com/a/28761247/309031 – Nik Sumeiko Feb 27 '15 at 10:45
2

Assuming that you want to remove the attributes to element, you can use something like

$(element).removeAttr($.makeArray(element.attributes)
                       .map(function(item){ return item.name;})
                       .join(' '));

Note that this will work only with jQuery 1.7+

Sujay
  • 2,142
  • 22
  • 32
1

As of ES2015, you can use Array.from().

const el = document.body;
const attributes = Array.from(el.attributes);
attributes.forEach(attr => el.removeAttributeNode(attr));
jabacchetta
  • 36,224
  • 7
  • 53
  • 71
0
var $newBody = $('<body>');
$newBody.append( $('body').contents() );
$('body').replaceWith( $newBody );

Something like this might work.

Stefan Kendall
  • 64,006
  • 65
  • 247
  • 399
  • 3
    Replacing the `body` has the side-effect of losing any JavaScript/jQuery references pointing to it, though, including any event handlers on it. – bobince Aug 29 '10 at 02:01
  • onclick, etc. are attributes from an XHTML viewpoint. Furthermore, it's trivial to make sure this runs before any other jQuery event binding. – Stefan Kendall Aug 29 '10 at 04:01
0

I don't know if it is the best way but it works

$('body').each(function(){
     var $body = $(this);
     var attributes = $.makeArray(this.attributes);

     $.each(attributes, function(indexInArray, valueOfElement) {
         $body.removeAttr(valueOfElement.name);
     });
});