How can I remove and add any id by pure JavaScript? Like
document.querySelector('div').classList.add('newClass') ;
and
document.querySelector('div').classList.remove('oldClass') ;
To remove the ID attribute from an element, call the removeAttribute() method on the element, passing the string 'id' as an argument.
IDs should be unique within a page, and all elements within a page should have an ID even though it is not necessary. You can add an ID to a new JavaScript Element or a pre-existing HTML Element.
The list items are added or removed using JavaScript functions addItem() and removeItem(). The list items are created using document. createElement() method and to create a text node, document. createTextNode() method is used and then this node is appended using appendChild() method.
Use the removeAttribute() method to remove the id attribute from an element, e.g. element. removeAttribute('id') . The removeAttribute method removes the passed in attribute from the element. Here is the HTML for the examples in this article.
Since ids are single strings it's just a matter of setting and unsetting it:
document.querySelector('div').id = 'whatever';
and to remove, just remove the attribute:
document.querySelector('div').removeAttribute('id');
There are plenty of ways to achieve this, to add new id:
document.querySelector('div').id = 'id_you_like';
document.querySelector('div').setAttribute("id", "id_you_like");
to remove the id attribute:
document.querySelector('div').removeAttribute('id');
document.querySelector('div').setAttribute("id", "");
Although you can set an empty(null) id for elements, it is not a good practice.
According to the W3C:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
If you use jQuery
:
$('div').attr('id', 'id_you_like');
$('div').removeAttr('id');
Something like this,
document.getElementById("before").id = "newid";
console.log(document.getElementById("newid").id)
//or
document.querySelector('div').id="newid"
<div id="first">
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With