How to Add ID to Element Using JavaScript
-
Use
setAttribute()
Function to Addid
to an Element in JavaScript -
Add
id
to Pre-Existing Element Using JavaScript -
Add
id
to New Element Using JavaScript
The id
attribute plays a vital role in JavaScript, which relates to a certain element suitable with the getElementById()
function. The id
must be unique in the HTML page because they help get the HTML element’s values and content later.
With the importance of the id
attribute, this tutorial teaches how to add the id
attribute to a pre-existing or new HTML element using JavaScript.
Use setAttribute()
Function to Add id
to an Element in JavaScript
For pre-existing and new HTML elements, setAttribute()
function and .id
property is used. The setAttribute()
takes two parameters.
The first is the attribute name, and the second is the attribute’s value. For instance, the first parameter would be id
, and the second can be any string to add the id
attribute to that particular element.
On the other hand, we can directly assign the id
attribute’s value to the .id
property. We will use the following HTML startup code to add an id
to a pre-existing and new element.
HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>Add IDs</title>
</head>
<body>
<h1 id="First Heading">My First Heading</h1>
<p id="firstParagraph">My first paragraph.</p>
</body>
</html>
Add id
to Pre-Existing Element Using JavaScript
var firstP = document.getElementById('firstParagraph');
firstP.setAttribute('id', 'firstPracPara');
console.log(document.getElementById('firstPracPara').id);
firstP.id = 'newPracPara';
console.log(document.getElementById('newPracPara').id);
Output:
"firstPracPara"
"newPracPara"
We used two ways in the above code to add the id
attribute. First is setAttribute()
method and the second is .id
property.
Firstly, we get the element whose id’s value is firstParagraph
, use the setAttribute()
function to set a new value of the id
attribute, and print on the console to confirm that it is changed.
Now, the id
is changed from firstParagraph
to firstPracPara
. Let’s change it again by using the .id
property.
The latest value of id
is newPracPara
; printed it also on the console to confirm. You can see the above output.
Add id
to New Element Using JavaScript
var secondP = document.createElement('p');
secondP.setAttribute('id', 'secondPara');
console.log(secondP.id);
secondP.id = 'newPara';
console.log(secondP.id);
Output:
"secondPara"
"newPara"
Here, we are creating a new element first using createElement()
function and then use setAttribute()
method and .id
property to add id
.