如何使用Javascript从DOM元素中删除属性?

时间:2013-09-12 17:42:26

标签: javascript html

我正在尝试使用javascript从DOM节点中删除属性:

<div id="foo">Hi there</div>

首先我添加一个属性:

document.getElementById("foo").attributes['contoso'] = "Hello, world!";

然后我删除它:

document.getElementById("foo").removeAttribute("contoso");

除了属性仍在那里。

然后我尝试真的删除它:

document.getElementById("foo").attributes['contoso'] = null;

现在它是null,与启动时不同,为undefined

从元素中删除属性的正确方法是什么?

jsFiddle playground

注意:使用属性contoso替换属性required,您就会明白i'm trying to do.

州表

                       foo.attributes.contoso  foo.hasAttribute("contoso")
                       ======================  ===========================
Before setting         undefined               false
After setting          Hello, world!           false
After removing         Hello, world!           false
After really removing  null                    false

1 个答案:

答案 0 :(得分:16)

不要使用attributes集合来处理属性。而是使用setAttributegetAttribute

var foo = document.getElementById("foo");

foo.hasAttribute('contoso'); // false
foo.getAttribute('contoso'); // null

foo.setAttribute('contoso', 'Hello, world!');

foo.hasAttribute('contoso'); // true
foo.getAttribute('contoso'); // 'Hello, world!'

foo.removeAttribute('contoso');

foo.hasAttribute('contoso'); // false
foo.getAttribute('contoso'); // null, 

// It has been removed properly, trying to set it to undefined will end up
// setting it to the string "undefined"
相关问题