This post will describe the procedure for adding an Id to an element in JavaScript.
How to Add ID to Element Using JavaScript?
To add the id to an element, the “setAttribute()” method is used. It requires two parameters, the “name” of the attribute is the first parameter, such as “id” and its value is a second parameter, such as “abc”.
Syntax
The given syntax id used for the setAttribute() method:
There are two ways for adding an Id to an element in JavaScript:
The given examples will demonstrate both ways one by one!
Example 1: Add ID by Creating New Element in JavaScript Using setAttribute() Method
In this example, we will create an HTML heading by JavaScript and set its id and the innerText for the DOM element.
In the JavaScript file, create an HTML element “h3” using the “createElement()” method:
Set the unique id to the heading using the “setAttribute()” method:
Here, the method takes two arguments:
- The “id” is the first argument that is the attribute name.
- The “heading” is the value of the id as a second attribute.
Get the reference of the HTML body tag using the “querySelector()” method:
Add the heading “h3” to the body, using the “appendChild()” method by passing the element as an argument:
Now, set the text for the element that will show on the DOM using the “getElementsByTagName()” with the “innerHTML” property:
Output
The output signifies that the heading is successfully created with its id that is set by using the “setAttribute()” method.
Example 2: Add ID to Existing Element Using setAttribute() Method
Let’s try to add a new id to the existing HTML element in JavaScript.
In an HTML file, create a heading with <h3> tag and assign an id to it using the “id” attribute:
The corresponding HTML output will be:
Now, in the JavaScript file, first, get the reference of the element using its assigned id with the help of the “getElementById()” method and store it in a variable “setId”:
Set the new id “heading1” to the element using the “setAttribute()” method:
Output
The above output indicates that the id of the HTML element heading is now “heading1” which is set by the JavaScript “setAttribute()” method.
Conclusion
For adding an id to an element, use the JavaScript “setAttribute()” method. There are two ways for adding an id to an element in JavaScript, add an id by creating a new element or add an id to the existing HTML element in JavaScript. This post described the procedure for adding an ID to an element in JavaScript.