In this Answer, we will look at how to create elements in a standard HTML document using JavaScript. We often need to render content, images, or hyperlinks as the traffic on our website interacts with it.
The document.createElement()
method allows us to create HTML elements on the go. Developers can create new elements efficiently using this method and later append them to the HTML document using document.appendChild()
.
Note: To read more on
document.appendChild()
, please refer to this link.
var element = document.createElement("elementName");
The parameter that is necessary to understand the working of the method is the one below:
elementName
: This string
specifies the type of HTML element we want to create.
Note: The
elementName
parameter specifies the particular HTML element that we want to create, for instance, a<p>
tag. If the element specified is not recognized, an unknown element is created with the type as defined by the user.
The document.createElement()
method returns the newly created element.
Let's look at its implementation with the help of a code example:
Note: The code example above illustrates the creation of the
<div>
element using thedocument.createElement()
method. However, we should note that this method supports the creation of any valid HTML elements such asp
ora
and so on.
Lines 5–7: In this piece of code, we have a parent <div>
which encapsulates a <button>
tag. This <button>
tag listens for the onclick
event and triggers the createEle()
function.
Lines 9–21: These lines contain our method, namely createEle()
, enclosed in <script>
tags. The method is described as follows:
Line 10: Here, we declare a variable divCreated
that is initially set to the value false
. This variable ensures that only one <div>
is created.
Line 14: We create a <div>
using the document.createElement()
method and store the return value in a variable named div
.
Line 15: We populate the newly created <div>
by assigning placeholder text of our choice, as seen in the output tab above.
Lines 16–17: This is where we first fetch the parent <div>
using document.getElementById()
method and append the newly created one using the document.appendChild()
method.
Free Resources