Remove the ID attribute from an Element using JavaScript

avatar

Borislav Hadzhiev

Sat Jan 08 20222 min read

Remove the ID attribute from an Element using JavaScript #

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.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box" id="box">Box content 1</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); // โœ… Remove ID attribute box.removeAttribute('id'); // โœ… Or set the attribute to another value // box.setAttribute('id', 'another-id');

We used the removeAttribute method to remove the id attribute from the element.

The only parameter the method takes is the name of the attribute to be removed.

If the attribute does not exist on the element, the removeAttribute method returns without throwing an error.

If you need to change the id attribute of the element, you don't have to use the removeAttribute method, instead you can use setAttribute.

index.js
const box = document.getElementById('box'); // โœ… Or set the attribute to another value box.setAttribute('id', 'another-id'); console.log(box.id); // ๐Ÿ‘‰๏ธ "another-id"

We used the setAttribute method to set the id attribute on the element.

The setAttribute method takes 2 parameters:

  1. name - the name of the attribute whose value is to be set.
  2. value - the value to assign to the attribute.
If the attribute already exists on the element, the value is updated, otherwise a new attribute is added with the specified name and value.

If you need to get the value of the element's id attribute, you can either access the id property directly or use the getAttribute() method.

index.js
const box = document.getElementById('box'); // โœ… Or set the attribute to another value box.setAttribute('id', 'another-id'); console.log(box.getAttribute('id')); // ๐Ÿ‘‰๏ธ "another-id"

The only parameter the getAttribute method takes is the name of the attribute to be returned.

If the attribute does not exist on the element, a null value or an empty string is returned, depending on the browser's implementation.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee