简体   繁体   中英

add and remove id by pure 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') ;

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>

To create an element an assign id

var div = document.createElement('div');
div.id = 'myId';

Or you can try if x is your element. set your attribute Id

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM