![](/img/trans.png)
[英]How to remove a style attribute from a span element using Vanilla JavaScript
[英]How to remove an attribute from a DOM element using Javascript?
我正在嘗試使用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
,這與它開始時不同,這是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
不要使用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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.