如何使用 Javascript 从 DOM 元素中删除属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18770925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove an attribute from a DOM element using Javascript?
提问by Ian Boyd
i am trying to use javascript to remove an attribute from a DOM node:
我正在尝试使用 javascript 从 DOM 节点中删除属性:
<div id="foo">Hi there</div>
First i add an attribute:
首先我添加一个属性:
document.getElementById("foo").attributes['contoso'] = "Hello, world!";
Then i remove it:
然后我删除它:
document.getElementById("foo").removeAttribute("contoso");
Except the attribute is still there.
除了属性仍然存在。
So then i try to reallyremove it:
那么我尝试真正删除它:
document.getElementById("foo").attributes['contoso'] = null;
And now it's null
, which is different than when it started, which was undefined
.
现在是null
,这与开始时不同,后者是undefined
。
What is the correct way to remove an attribute from an element?
从元素中删除属性的正确方法是什么?
Note: Replace the attribute contoso
, with the attribute required
, and you'll understand what i'm tryingto do.
注意:更换属性contoso
,与属性required
,你就会明白我正在努力做的事。
State table
状态表
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
回答by Paul
Don't use the attributes
collection to work with attributes. Instead use setAttributeand getAttribute:
不要使用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"