簡體   English   中英

如何使用Javascript從DOM元素中刪除屬性?

[英]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

從元素中刪除屬性的正確方法是什么?

jsFiddle游樂場

注意 :更換屬性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集合來處理屬性。 而是使用setAttributegetAttribute

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM