What is the createElement() method in DOM?
The createElement() method in DOM
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.
Syntax
var element = document.createElement("elementName");
Parameters
The parameter that is necessary to understand the working of the method is the one below:
elementName: Thisstringspecifies the type of HTML element we want to create.
Note: The
elementNameparameter 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.
Return value
The document.createElement() method returns the newly created element.
Code
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 asporaand so on.
Explanation
Lines 5–7: In this piece of code, we have a parent
<div>which encapsulates a<button>tag. This<button>tag listens for theonclickevent and triggers thecreateEle()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
divCreatedthat is initially set to the valuefalse. This variable ensures that only one<div>is created.Line 14: We create a
<div>using thedocument.createElement()method and store the return value in a variable nameddiv.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>usingdocument.getElementById()method and append the newly created one using thedocument.appendChild()method.
Free Resources