. Advertisement .
. Advertisement .
Creating an element with an ID means assigning a unique id to an element. Every element in a website page should have a unique ID. Let’s talk about how to create an element with ID attribute using JS
How to Create an element with ID attribute using JS
Creating an ID for an element is not a hard one to crack. To this, we need to use the ‘
document.createElement()' for the purpose of creating the element. Once we create the element, we need to set the ID for the element using the ‘
setAttribute’ Method. And, when it comes to adding the element on your web page, use the ‘
Let’s take a look at the HTML code:
<!DOCTYPE html> <html lang="en"> <head> <title>Create an element with ID attribute using JS</title> </head> <body> <h1 id="Heading1"> Heading 1</h1> <p id="Paragraph1">Paragraph 1</p> <script src="main.js"></script> </body> </html>
When we have to create an element, we use the
document.createElement() method. To set a unique ID, we use the
setAttribute() method for that element.
var second_Paragraph = document.createElement('p'); second_Paragraph.setAttribute('id','secondParagraph'); console.log(second_Paragraph.id); second_Paragraph.id="newsParagraph"; console.log(second_Paragraph.id);
If an element already exists and you want to add an ID to it, you can do it like this
var firstP = document.getElementById("firstParagraph"); firstP.setAttribute("id","firstPracPara"); console.log(document.getElementById("firstPracPara").id); firstP.id="newPracPara"; console.log(document.getElementById("newPracPara").id);
With the setAttribute method, the .id property is also used to set a new ID, and then try to print the console to see the result you get in return.
Using appendChild() Method
After creating an element with a specified name and adding an ID, you can use the
appendChild() method to add the element to the page. With this method, you can append the element to the end of the parent element. Let’s go through the code
// selecting parent element var parent = document.getElementById('parent'); var child = document.createElement('p'); child.innerHTML = 'Paragraph 3'; parent.appendChild(child);
<div id="parent"> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> </div>
It is noted you can append only one element at a time using the
And that’s how you can create an element with ID attribute using JS. Three methods have been discussed to create ID for an element. First, we created an element, then set ID, and in the end, we append it.
I hope you find it helpful! Code well! And don’t forget to drop a comment below as your feedback is appreciated!