Sunday, 30 September 2018

JavaScript: appendChild: Create a child to node

By using ‘appendChild’ method, you can add a child to parent node.

Syntax
parentNode.appendChild(childNode);

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