how to remove all attributes from <body> with js or jquery
how to remove all attributes from with js or jquery. (I don't know what is the attr开发者_StackOverflow社区ibutes in the body, i want remove all them)
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();
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+
As of ES2015, you can use Array.from().
const el = document.body;
const attributes = Array.from(el.attributes);
attributes.forEach(attr => el.removeAttributeNode(attr));
var $newBody = $('<body>');
$newBody.append( $('body').contents() );
$('body').replaceWith( $newBody );
Something like this might work.
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);
});
});
精彩评论