How to Assign Id to an HTML Element Dynamically in JavaScript?

Ids are unique identifiers of HTML elements. Each Id refers to a particular HTML element and it should always be unique within a page.

There are two ways to assign an Id to an HTML element. First, directly add the id to the HTML element using the id attribute eg. <div id="myId"></div>.

The second way is to add it dynamically using JavaScript.

To assign an Id to an HTML element in JavaScript, you can use the setAttribute() method of the DOM. The setAttribute() method takes two parameters. First, the name of the attribute which in our case is id, and second is the value of the attribute.

setAttribute(name, value)

Let’s say we have a div element in our HTML file:

<div>This is a div element.</div>

We want to add an Id myId to this div element dynamically.

To do that the first thing we need to do is get the element using any DOM selector method such as getElementsByTagName(), querySelector(), etc.

After that, we can use the setAttribute() method to set the value of the Id attribute.

See the following code:

// Get the element
const element = document.querySelector('div');

// Set Id value
element.setAttribute('id', 'myId');

// Output: myId

The above code successfully adds an Id myId to the div element.

Assign Id to Dynamically Created Elements

You can also use the setAttribute() method to assign Id to dynamically created elements.

Let’s say we have a div element in our HTML file with an Id myDiv. We want to dynamically create a paragraph under this div and assign an id myPara to it with JavaScript.

<div id="myDiv">
    <!--Paragraphs will be added here-->

This can be achieved in the following steps:

  1. Get the parent div element with any DOM selector method such as getElementById().
  2. Create the <p> element using the createElement() method.
  3. Add some text to the <p> element using the innerText property and assign an id to it using the setAttribute() method.
  4. Append the paragraph to the parent div element using the appendChild() method.

See the following code:

// Get the parent div
const div = document.getElementById('myDiv');

// Create a <p> element
const para = document.createElement('p');

// Set id and inner text
para.innerText = 'This is a paragraph';

// Append <p> element to the div

After running the above code, the <p> elemement will be added under the <div> with an id myPara. See the following image:

Assign id to HTML elements dynamically

Thanks for reading.


  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.