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
2010-08-29 01:57:44
This is what i need.Thank you very much.
faressoft
2010-08-29 02:02:51
+1 great solution. You should accept the answer @faressoft
Marko
2010-08-29 02:30:26
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
2010-08-29 12:39:48
Array-like access to `attributes` does seem to work, independently of the issues with property-name access.
bobince
2010-08-29 15:41:47
A:
var $newBody = $('<body>');
$newBody.append( $('body').contents() );
$('body').replaceWith( $newBody );
Something like this might work.
Stefan Kendall
2010-08-29 01:58:28
Replacing the `body` has the side-effect of losing any JavaScript/jQuery references pointing to it, though, including any event handlers on it.
bobince
2010-08-29 02:01:46
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
2010-08-29 04:01:16
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
2010-08-29 04:13:17