我正在尝试使用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
。
从元素中删除属性的正确方法是什么?
注意:使用属性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
答案 0 :(得分:16)
不要使用attributes
集合来处理属性。而是使用setAttribute和getAttribute:
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"