Sunday 30 September 2018

JavaScript: createElement: Create new Element

By using createElement method, you can create an element.

Syntax
document.createElement(nodeName);

Example
document.createElement("p");

Above statement creates a paragraph element.

process.js
function addData(){
 var para = document.createElement("p");
 var textNode = document.createTextNode("Good Morning");
 para.appendChild(textNode);
 
 var div = document.getElementById("data1");
 div.appendChild(para);
}

changeDom.html
<!DOCTYPE html>

<html>

<head>
    <title>Change DOM</title>
    <script src="process.js"></script>
</head>

<body>

    <div id="data1">
    </div>

    <input type="button" value="click me" onclick="addData();" />

    </div>
</body>

</html>

Open changeDom.html in browser, it shows the button ‘cilck me’. For every click of the button, it adds new paragraph with text "Good Morning" to the browser window.



Previous                                                 Next                                                 Home

No comments:

Post a Comment