我正在尝试使用javascript从DOM节点中删除属性:
<div id="foo">Hi there</div>
Run Code Online (Sandbox Code Playgroud)
首先我添加一个属性:
document.getElementById("foo").attributes['contoso'] = "Hello, world!";
Run Code Online (Sandbox Code Playgroud)
然后我删除它:
document.getElementById("foo").removeAttribute("contoso");
Run Code Online (Sandbox Code Playgroud)
除了属性仍然存在.
那么我试着真正删除它:
document.getElementById("foo").attributes['contoso'] = null;
Run Code Online (Sandbox Code Playgroud)
现在它是null,它与它开始时不同,这是undefined.
从元素中删除属性的正确方法是什么?
注意:使用属性替换属性contoso,required您将了解我正在尝试做什么.
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
Run Code Online (Sandbox Code Playgroud)
Pau*_*aul 17
不要使用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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10383 次 |
| 最近记录: |