使用纯 JavaScript 添加和删除 ID。

15

如何使用纯JavaScript删除和添加id?类似于

document.querySelector('div').classList.add('newClass') ;

and

document.querySelector('div').classList.remove('oldClass') ;

1
请阅读[询问]。 - Rafael
4个回答

25

由于ID是单个字符串,所以只需要设置和取消设置它:

document.querySelector('div').id = 'whatever';

要移除,只需移除该属性:

document.querySelector('div').removeAttribute('id');

3
removeAttribute是正确的方法。空的id属性不被允许(虽然在大多数主流浏览器中这不会引起问题)。 - Paul
1
id 属性必须至少包含一个字符:https://www.w3.org/TR/html51/dom.html#the-id-attribute - Paul
修改了答案,只反映了正确的用法。 - Matt Coady
这不是正确答案。removeAttribute将会移除整个元素,而不仅仅是属性。 - 6rchid
@6rchid没错。你可以自己测试或查看MDN文档。你可能在想remove方法,它是用于从DOM中删除元素的方法。 - Matt Coady

7

有很多方法可以实现此目的,要添加新的id:

document.querySelector('div').id = 'id_you_like';
document.querySelector('div').setAttribute("id", "id_you_like");

删除id属性:

document.querySelector('div').removeAttribute('id');
document.querySelector('div').setAttribute("id", "");

虽然您可以为元素设置空(null)id,但这不是一个好习惯。

根据W3C的规定:

ID和NAME令牌必须以字母([A-Za-z])开头,后面可以跟任意数量的字母、数字([0-9])、连字符(“-”)、下划线(“_”)、冒号(“:”)和句点(“.”)。

如果您使用jQuery

$('div').attr('id', 'id_you_like');
$('div').removeAttr('id');

3

类似这样的内容,

document.getElementById("before").id = "newid";
console.log(document.getElementById("newid").id)
//or
document.querySelector('div').id="newid"
<div id="first">
</div>


-1
创建一个元素并分配ID。
var div = document.createElement('div');
div.id = 'myId';

或者你可以尝试一下,如果x是你的元素,就设置你的属性Id

x.setAttribute('id','myCoolElement')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接