微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试使用 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,这是不同于它开始,这是未定义的.

从元素中删除属性的正确方法是什么?

jsFiddle playground

注意:替换属性contoso,具有所需的属性,你会明白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

解决方法

不要使用属性集合来处理属性.而是使用 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"

原文地址:https://www.jb51.cc/js/151623.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐