Add an ID attribute to an Element using JavaScript

avatar

Borislav Hadzhiev

Fri Jan 07 20222 min read

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 above, I can see that the id attribute is set on the element.

id attribute set

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