views:

84

answers:

3

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)

+9  A: 

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
This is what i need.Thank you very much.
faressoft
+1 great solution. You should accept the answer @faressoft
Marko
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
Array-like access to `attributes` does seem to work, independently of the issues with property-name access.
bobince
A: 
var $newBody = $('<body>');
$newBody.append( $('body').contents() );
$('body').replaceWith( $newBody );

Something like this might work.

Stefan Kendall
Replacing the `body` has the side-effect of losing any JavaScript/jQuery references pointing to it, though, including any event handlers on it.
bobince
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
A: 

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);
     });
});
cj_battista
Is "each" really necessary here?
Stefan Kendall