[英]How to remove an attribute from a DOM element using Javascript?
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 really remove 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? 从元素中删除属性的正确方法是什么?
jsFiddle playground jsFiddle游乐场
Note : Replace the attribute contoso
, with the attribute required
, and you'll understand what i'm trying to do. 注意 :更换属性
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
Don't use the attributes
collection to work with attributes. 不要使用
attributes
集合来处理属性。 Instead use setAttribute and getAttribute : 而是使用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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.