How to add an ID to element in JavaScript

Key takeaways:

  • There are two methods to add IDs:

    • Using the id property: The simplest method for assigning an ID to an existing element.

    • Using setAttribute(): A versatile approach to add or modify any attribute, including IDs.

  • IDs uniquely identify HTML elements, making it easy to select and manipulate them with JavaScript.

  • Adding IDs dynamically is useful for new elements, managing similar elements, or updating elements based on user interaction.

  • IDs should be unique on a page, ensuring clear, targeted selection without conflicts.

In web development, each HTML element can be uniquely identified with an ID, allowing us to style, manipulate, or reference it in JavaScript easily. IDs can enhance the code by providing a straightforward way to select elements and perform actions on them. In this Answer, we’ll learn how to add an ID to an element using JavaScript, ensuring a smooth way to control our HTML elements dynamically.

What is an ID in JavaScript?

IDs are essential in JavaScript. They refer to a particular element compatible with the getElementById() method, which returns it with the given property. IDs should be unique within a page, and all elements within a page should have an ID, even though it is not necessary.

Why add an ID dynamically

Sometimes, when working with JavaScript, we need to assign IDs to elements after they have been created or modified. This dynamic addition of IDs is helpful when:

  • Creating new elements that need to be accessed later.

  • Assigning unique identifiers in scenarios with multiple similar elements.

  • Updating an element based on specific user actions or data.

Let’s dive into how we can add an ID to an element dynamically in JavaScript.

Adding an ID when creating a new element

When creating a new element in JavaScript, we can also add an ID directly before appending it to the document. This method is helpful when dynamically generating elements that need unique identifiers.

// Create a new paragraph element
const terms = document.createElement('p');
// Assign an ID to the new element
terms.id = 'para-1';
// Add content to the paragraph
terms.textContent = "This is a dynamically created paragraph.";
// Append it to the body or any other container
document.body.appendChild(terms);
Adding ID when creating a new element

In the above code:

  • Line 2: We create a new paragraph (<p>) element.

  • Line 5: We assign para-1 as the ID of terms.

  • Line 8: We set the text content of the paragraph.

  • Line 11: We append terms to the body, making it visible on the page.

How to add an ID to existing elements in JavaScript

First, we need to find the element. This can be done using:

In JavaScript, we can add or change an element’s ID in just a few lines of code. Here, we’ll learn multiple methods to achieve this.

Method 1: Using the id property

The easiest way to add an ID to an element in JavaScript is by using the id property. This method allows us to directly assign a new ID to an existing element.

// Select the element (e.g., using querySelector)
var intro = document.querySelector('.intro');
// Assign a new ID
intro.id = "newID";
Adding ID using the ID property

In the above code:

  • Line 2: We select the desired element using a JavaScript selector method like querySelector(). In our example, we select an intro element.

  • Line 3: We use the id property to assign newID as the ID of intro element.

Method 2: Using setAttribute() to add an ID

Another method to add an ID to an element is by using the setAttribute() method. This function allows to set any attribute on an element, including an ID.

// Select an existing element
let intro = document.querySelector('.intro');
// Use setAttribute to add an ID
intro.setAttribute('id', 'Introduction_1');
Adding ID using the setAttribute() method

Explanation:

  • Line 2: We select an existing intro element.

  • Line 5: We use setAttribute() to assign the ID Introduction_1 to intro.

The setAttribute() method is particularly useful if we’re working with multiple attributes on an element or need a more flexible approach to attribute management.

Coding example

Now, let’s interact with a coding example by clicking the “Run” button in the below widget.

Knowledge test

Let’s attempt a short quiz to assess your understanding.

1

Which method directly assigns an ID to an element in JavaScript?

A)

getElementById("newID")

B)

element.id = "newID"

C)

setAttribute("id", "newID")

D)

setId(element, "newID")

Question 1 of 20 attempted

Conclusion

Adding an ID to an HTML element in JavaScript can simplify and streamline DOM manipulation. By using methods like id and setAttribute(), we can dynamically assign IDs, providing flexibility and control when working with dynamic content. As you practice these methods, remember to keep IDs unique within the page to avoid conflicts and improve the readability and efficiency of the code.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


How do I add an ID attribute to a div element?

To add an ID to a div element in JavaScript, you can use either the id property or the setAttribute() method.

// Using the id property
const divElement = document.createElement("div");
divElement.id = "uniqueID";

// Using setAttribute()
divElement.setAttribute("id", "uniqueID");

// Append div to the body or any other element
document.body.appendChild(divElement);

Both methods assign uniqueID to the divElement, making it accessible by that ID later in your code.


How to add an ID to an array element in JavaScript

JavaScript arrays are primarily for storing values and don’t support direct assignment of an ID attribute to elements as objects do. However, you can store objects in the array and assign an ID property within each object. Here’s an example:

// Creating an array of objects, each with an ID
const elementsArray = [
  { id: "element1", content: "This is element 1" },
  { id: "element2", content: "This is element 2" },
  { id: "element3", content: "This is element 3" }
];

// Accessing the ID of the first element
console.log(elementsArray[0].id); // Outputs: "element1"

If you’re working with DOM elements, store the element with its ID in the array, as shown here:

const div1 = document.createElement("div");
div1.id = "div1";

const div2 = document.createElement("div");
div2.id = "div2";

const elementsArray = [div1, div2];

How to get an element using an ID in JavaScript

Use the getElementById() method to access an element by its ID. This method returns the element if it exists or null if it doesn’t.

const element = document.getElementById("uniqueID");

if (element) {
  console.log("Element found:", element);
} else {
  console.log("Element not found");
}

In this example, uniqueID is the ID of the element you’re trying to access.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved