Last updated: Mar 5, 2024
Reading timeยท2 min

To add an id attribute to an element:
document.querySelector() method.setAttribute() method to add an id attribute to the element.Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <title>bobbyhadz.com</title> <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.
const box = document.querySelector('.box'); // ๐๏ธ set `id` attribute on the element box.setAttribute('id', 'box');

We used the document.querySelector() method to select the element by its class.
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.
const box = document.querySelector('.box'); // ๐๏ธ set `id` attribute on the 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:
name - the name of the attribute whose value is to be set.value - the value to assign to the attribute.If you need to get the value of the attribute, use the getAttribute() method.
const box = document.querySelector('.box'); // ๐๏ธ set `id` attribute on the 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.
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.

You can learn more about the related topics by checking out the following tutorials: