Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add and remove id by pure JavaScript

Tags:

javascript

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') ;
like image 252
user10965341 Avatar asked Jan 25 '19 03:01

user10965341


People also ask

How do you remove an element id?

To remove the ID attribute from an element, call the removeAttribute() method on the element, passing the string 'id' as an argument.

Can you add an id to an element in JavaScript?

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.

How add and remove data in JavaScript?

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.

How do I remove my property from id?

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.


3 Answers

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');
like image 170
Matt Coady Avatar answered Oct 19 '22 03:10

Matt Coady


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');
like image 40
Elyas Hadizadeh Avatar answered Oct 19 '22 05:10

Elyas Hadizadeh


Something like this,

document.getElementById("before").id = "newid";
console.log(document.getElementById("newid").id)
//or
document.querySelector('div').id="newid"
<div id="first">
</div>
like image 3
dhanu10896 Avatar answered Oct 19 '22 04:10

dhanu10896