如何从js或jquery中删除所有属性

时间:2010-08-29 01:53:12

标签: javascript jquery attributes

如何使用js或jquery删除所有属性。 (我不知道身体中的属性是什么,我想要删除所有属性)

5 个答案:

答案 0 :(得分:19)

您可以使用DOM Level 1 Core attributes属性作为列表访问属性。简单的JS:

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

或者穿着jQuery插件衣服:

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

$('body').removeAllAttrs();

答案 1 :(得分:2)

假设您要将属性移除到element,您可以使用类似

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

请注意,这仅适用于jQuery 1.7 +

答案 2 :(得分:0)

var $newBody = $('<body>');
$newBody.append( $('body').contents() );
$('body').replaceWith( $newBody );

这样的事情可能有用。

答案 3 :(得分:0)

我不知道这是否是最好的方式,但它有效

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

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

答案 4 :(得分:0)

从ES2015开始,您可以使用Array.from()

const el = document.body;
const attributes = Array.from(el.attributes);
attributes.forEach(attr => el.removeAttributeNode(attr));