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'); console.log(element.id); // 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--> </div>
This can be achieved in the following steps:
- Get the parent div element with any DOM selector method such as
getElementById()
. - Create the
<p>
element using thecreateElement()
method. - Add some text to the <p> element using the
innerText
property and assign an id to it using thesetAttribute()
method. - 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.setAttribute('id','myPara'); para.innerText = 'This is a paragraph'; // Append <p> element to the div div.appendChild(para);
After running the above code, the <p> elemement will be added under the <div> with an id myPara
. See the following image:
Thanks for reading.