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

前端之家收集整理的这篇文章主要介绍了如何使用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.f2er.com/js/151623.html

猜你在找的JavaScript相关文章