HTML DOM createElement() method


The HTML DOM createElement() method is used for creating an HTML element dynamically using JavaScript. It takes the element name as the parameter and creates that element node. You need to use the appendChild() method to have the newly created element as part of DOM .

Syntax

Following is the syntax for createElement() method −

document.createElement(nodename)

Example

Let us look at an example for the createElement() method −

<!DOCTYPE html>
<html>
<body>
<h1>createElement() example</h1>
<p>Click the below button to create more buttons</p>
<button onclick="createButton()">CREATE</button>
<br><br>
<script>
   var i=0;
   function createButton() {
      i++;
      var btn = document.createElement("BUTTON");
      btn.innerHTML="BUTTON"+i;
      var br= document.createElement("BR");
      document.body.appendChild(btn);
      document.body.appendChild(br);
   }
</script>
</body>
</html>

Output

This will produce the following output −

On clicking the CREATE button three times. One click for one button −

In the above example −

We have created a button CREATE that will execute the createButton() method on being clicked by the user.

<button onclick="createButton()">CREATE</button>

The createButton() function creates a <button> element using the createElement() method of the document object. Using the innerHTML, we set the text that will be displayed on the top of the button. We create another element <br> using the createElement() method of the document object. The <button> element and the <br> element are then appended to the document body using the appendChild() method −

var i=0;
function createButton() {
   i++;
   var btn = document.createElement("BUTTON");
   btn.innerHTML="BUTTON"+i;
   var br= document.createElement("BR");
   document.body.appendChild(btn);
   document.body.appendChild(br);
}
raja
Published on 08-Aug-2019 16:47:45
Advertisements