javascript - 如何使用 Javascript 从 DOM 元素中删除属性?

标签 javascript html

我正在尝试使用 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 playground

注意:将属性 contoso 替换为属性 required,您将了解 i'm trying to do. 的含义

状态表

                       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"

关于javascript - 如何使用 Javascript 从 DOM 元素中删除属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18770925/

相关文章:

javascript - 使用 JQuery 或 CSS 从 html 元素中删除所有 css?

javascript - HTML 动态/响应元素定位

php - $_GET ["q"] ... $q==1 echo "yadda yadda yadda!"... 返回未定义。使用 XAMPP 的本地主机

javascript - Mobile Safari 的日期/时间类型输入字段触发了哪些事件?

javascript - 在应用程序框架中处理异步 Javascript 代码的最佳实践

javascript - 在像 JavaScript 中的 `event.target` 这样的事件回调中, `this` 是否保证是 "click"的后代/等于 0x104567910 ?

javascript - CSS JavaScript 灯箱图库

html - Angular 7 动画 - 过渡不起作用

javascript - RxJS 等待上一次执行完成

javascript - 如何独立调用 d3.svg.line()?