Add an ID attribute to an Element using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Add an ID attribute to an Element using JavaScript #

To add an id attribute to an element:

  1. Select the element using the document.querySelector() method.
  2. Use the setAttribute() method to add an id attribute to 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">Example content</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.querySelector('.box'); // 👇️ set `id` attribute on element box.setAttribute('id', 'box');

We used the document.querySelector method to select the element by its class.

The method returns the first element within the document that matches the provided selector.

If no element matches the selector, the method returns null.

If you need to handle a scenario where the element is not found in the DOM, use the optional chaining (?.) operator when invoking the setAttribute() method to avoid getting an error.

index.js
const box = document.querySelector('.box'); // 👇️ set `id` attribute on element box?.setAttribute('id', 'box');

If the box variable stores a null value, the optional chaining (?.) operator will short-circuit returning undefined, instead of trying to call the setAttribute method on a null value.

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 attribute, use the getAttribute() method.

index.js
const box = document.querySelector('.box'); // 👇️ set `id` attribute on element box?.setAttribute('id', 'box'); // 👇️ "box" console.log(box.getAttribute('id'));

You might see examples online that directly set the id property on the element.

index.js
const box = document.querySelector('.box'); box.id = 'box'; // 👇️ "box" console.log(box.getAttribute('id'));

This is also a perfectly valid approach.

If I open my browser with the code from the example, I can see that the id attribute is set on the element.

id attribute set

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.