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: 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.

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 the document.createElement() method. However, we should note that this method supports the creation of any valid HTML elements such as p or a and 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 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.

Note: For more details, please visit to this link to explore more on document.getElementById() method of DOM.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved