How To Use HTML DOM CreateElement Method In JavaScript

admin_img Posted By Bajarangi soft , Posted On 25-09-2020

In Java Script we can create new buttons, text or input field on click of another button today we going to discuss how to use CreateElement method in java script

How To Use HTML DOM CreateElement Method In JavaScript

The createElement() method creates an Element Node with the specified name.

Tip: After the element is created, use the element.appendChild() or element.insertBefore() method to insert it to the document.

Syntax and Usage

document.createElement(nodename)
 

Parameter Values

nodename    String Required. The name of the element you want to create


Example(1)

HTML elements often contains text. To create a button with text, use the innerText or innerHTML properties of the element object:

<script>
    function add_button() {
        var btn = document.createElement("BUTTON");
        btn.innerHTML = "CLICK ME";
        document.body.appendChild(btn);
    }
</script>

In above example creating new buttons on click of button .


Example(2)
 
<button class="btn btn-primary" onclick="add_inputfield()">Click it</button>
   
<script>
    function add_inputfield() {
        var btn = document.createElement("Input");
        btn.innerHTML = "Button";
        document.body.appendChild(btn);
    }
</script>

In above example creating new Input fields on click of button .

Example(3)
<button onclick="add_paragraph()">Try it</button>

<script>
    function add_paragraph() {
        var para = document.createElement("P");
        para.innerText = "This is a paragraph.";
        document.body.appendChild(para);
    }
</script>


In above example creating a <p> element with some text, use innerText to set the text, and append it to the document.

Complete code for HTML DOM CreateElement Method In JavaScript

<!DOCTYPE html>
<html>
<head>
    <title>HTML DOM CreateElement Method In JavaScript</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
    <div class="text-center">
        <h1>HTML DOM CreateElement Method In JavaScript</h1>
    </div>
    <br>
    <div class="well">
        <button class="btn btn-primary" onclick="add_button()">Click it</button>
    </div>
    <br>
</div>
</body>
</html>
<script>
    function add_button() {
        var btn = document.createElement("Button");
        btn.innerHTML = "Button";
        document.body.appendChild(btn);
    }
</script>

 

Related Post