如何使用纯JavaScript删除和添加id?类似于
document.querySelector('div').classList.add('newClass') ;
and
document.querySelector('div').classList.remove('oldClass') ;
如何使用纯JavaScript删除和添加id?类似于
document.querySelector('div').classList.add('newClass') ;
and
document.querySelector('div').classList.remove('oldClass') ;
由于ID是单个字符串,所以只需要设置和取消设置它:
document.querySelector('div').id = 'whatever';
要移除,只需移除该属性:
document.querySelector('div').removeAttribute('id');
removeAttribute
是正确的方法。空的id属性不被允许(虽然在大多数主流浏览器中这不会引起问题)。 - Paulid
属性必须至少包含一个字符:https://www.w3.org/TR/html51/dom.html#the-id-attribute - PaulremoveAttribute
将会移除整个元素,而不仅仅是属性。 - 6rchidremove
方法,它是用于从DOM中删除元素的方法。 - Matt Coady有很多方法可以实现此目的,要添加新的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');
类似这样的内容,
document.getElementById("before").id = "newid";
console.log(document.getElementById("newid").id)
//or
document.querySelector('div').id="newid"
<div id="first">
</div>
var div = document.createElement('div');
div.id = 'myId';
或者你可以尝试一下,如果x是你的元素,就设置你的属性Id
x.setAttribute('id','myCoolElement')