How to Add an ID Attribute to an Element in JavaScript
When you're dynamically creating or manipulating elements in the DOM, you often need to assign them a unique id. This makes the element easy to select for styling with CSS or for later manipulation with JavaScript.
This guide will teach you the modern, standard method for adding an id attribute to an element by setting its id property directly. You will also learn about the setAttribute() method as a more general-purpose alternative.
The Modern Method (Recommended): The id Property
Every HTML element in the DOM has a directly accessible id property. Setting this property is the simplest, most readable, and most common way to assign an ID to an element.
For example, we have an element and we want to give it an ID so we can style or select it.
<div class="box">This element needs an ID.</div>
The solution is as follows:
- First, get a reference to the element.
- Then, simply assign a string to its
idproperty.
// Get the element
const box = document.querySelector('.box');
// Set its ID by assigning to the .id property
box.id = 'my-unique-box';
// Verify the result
console.log(box.id); // Output: "my-unique-box"
console.log(document.getElementById('my-unique-box'));
// Output: <div class="box" id="my-unique-box">...</div>
This is the recommended best practice for its clarity and directness.
An Alternative: The setAttribute() Method
The setAttribute() method is a more general-purpose way to set any HTML attribute on an element. It works perfectly for setting an id, but it's slightly more verbose for this specific task.
The logic: the setAttribute() method takes two arguments: the name of the attribute (as a string) and the value to set.
Solution:
const box = document.querySelector('.box');
// Set the 'id' attribute with its value
box.setAttribute('id', 'my-unique-box');
// Verify the result
console.log(box.id); // Output: "my-unique-box"
This achieves the exact same result as setting the .id property directly.
Best Practice: id vs. setAttribute()
So, which method should you use?
For setting an element's id, directly assigning to the .id property is preferred.
- Readability:
element.id = 'my-id'is slightly cleaner and more direct thanelement.setAttribute('id', 'my-id'). - Purpose: The
.idproperty is specifically designed for this attribute, whereassetAttribute()is a generic tool. Using the more specific tool often leads to clearer code.
While setAttribute() is a powerful and essential tool for setting other attributes (especially custom data-* attributes), for the common case of setting an id, the direct property assignment is the modern standard.
Practical Example: Creating and Identifying a New Element
A very common use case is to create a new element and immediately give it an ID for later reference.
// 1. Create a new element
const newParagraph = document.createElement('p');
// 2. Configure the element, including its ID
newParagraph.id = 'status-message';
newParagraph.textContent = 'Loading...';
newParagraph.style.color = 'blue';
// 3. Append the element to the DOM
document.body.appendChild(newParagraph);
// Now, we can easily find and update this element later using its ID
setTimeout(() => {
const statusMessage = document.getElementById('status-message');
if (statusMessage) {
statusMessage.textContent = 'Load complete!';
statusMessage.style.color = 'green';
}
}, 2000);
Conclusion
Adding an id to an element in JavaScript is a simple and fundamental task.
- The recommended best practice is to set the
idproperty directly on the element:element.id = 'your-new-id';. It is concise, readable, and clearly expresses your intent. - The
element.setAttribute('id', 'your-new-id')method is a perfectly valid alternative that is more general-purpose.
For clean and modern code, prefer the direct .id property assignment.