我正在尝试使用
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,这是不同于它开始,这是未定义的.
注意:替换属性contoso,具有所需的属性,你会明白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
解决方法
不要使用属性集合来处理属性.而是使用
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"