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”.
The given syntax id used for the setAttribute() method:
The given examples will demonstrate both ways one by one!
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:
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
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:
Set the new id “heading1” to the element using the “setAttribute()” method: