如何使用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"

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...