如何使用Javascript从DOM元素中删除属性? [英] How to remove an attribute from a DOM element using Javascript?
问题描述
< div id =foo 我试图使用javascript从DOM节点中删除属性: >您好< / div>
首先我添加一个属性:
document.getElementById(foo)。attributes ['contoso'] =Hello,world!;
然后移除它:
<$ p $ 。p> 的document.getElementById( 富)的removeAttribute( CONTOSO);
除了该属性仍然存在。
然后我尝试 删除它:
document.getElementById(foo)。 attributes ['contoso'] = null;
现在它是 null
,这是不同的比 undefined
。
从元素中删除属性的正确方法是什么?
注意:将属性 contoso
替换为所需的属性
,你就会明白什么是我是尝试做。
状态表
foo.attributes.contoso foo.hasAttribute(contoso)
====================== ======== ===================
在设置undefined false之前
设置Hello,world后! false
删除Hello,world! false
真正删除null false
Don不使用属性
集合来处理属性。请改用 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,
//已将它正确删除,试图将其设置为undefined将最终返回
//将其设置为字符串undefined
i am trying to use javascript to remove an attribute from a DOM node:
<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
.
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 trying to do.
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
Don't use the attributes
collection to work with attributes. Instead use setAttribute and 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"
这篇关于如何使用Javascript从DOM元素中删除属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!