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

17
我试图使用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

注意:用属性required替换属性contoso,你就会明白我试图做什么了。

状态表

                       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

可能是重复的问题:如何从JavaScript对象中删除属性 - cske
http://jsfiddle.net/7su7C/1/ - cske
3
@cske(以及其他认为它是重复的人),不要混淆从Javascript对象中删除一个property和从DOM对象中删除一个attribute。如果这是一个Javascript对象,它就可以运行。 - Ian Boyd
删除操作可以使用set/get方法更加规范,就像一只鸭子走起路来像鸭子,游泳时像鸭子,叫声也像鸭子一样... 当你使用JavaScript接口访问DOM对象(浏览器内部)属性。 - cske
1个回答

24

不要使用 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"

有没有指南表明要避免访问DOM对象的.attributes集合?如果是这样的话,那么我要重新思考我的大量代码了。 - Ian Boyd
@IanBoyd 我不确定是否有任何特定的参考资料。我从未直接使用过它。我知道有一些不一致之处。在 IE8 中,当您遍历它时,您会得到所有可能的属性,而在 IE9 中,您只会得到已定义的属性。根据您在问题中描述的行为,它似乎也与 removeAttribute 不兼容。 - Paul
@Paulpro,为什么你使用 foo.hasAttribute('x') 而不是 foo.x === undefined - Pacerier
foo.x 是一个属性,而不是一个特性,并且可能与 foo.get attribute('x') 的值不同。 - Paul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接