HTML DOM createElement(), createTextNode() and appendChild() Method

The createElement() method is used to create an HTML element node with the specified name. The basic syntax of createElement() is as follows :
  var elementNode = document.createElement(nodename);
when the element node is created then we need to create a text node for our element node, because the HTML elements often consists of both an element node and a text node. Now the createTextNode() method creates a Text Node. The syntax of createTextNode() is as follows :
  var textNode = document.createTextNode(text);
where the text is text of textNode. Now we have to append the textNode into the element node by using appendChild() method. It appends a node as the last child of a node. The syntax is as follows :
  elementNode.appenChild(textNode);
Now Lets see an Example :
<html>
<body>
  <script>
    // creating a div element
    var elementNode = document.createElement('div');
    var textNode = document.createTextNode('Hello world This is Text inside div.');
    elementNode.appendChild(textNode);
    document.body.appendChild(elementNode);

    // creating a button control
    var buttonNode = document.createElement('button');
    buttonNode.setAttribute('onclick', 'alert("hello there!");');
    var textNode = document.createTextNode('Click Here');
    buttonNode.appendChild(textNode);
    document.body.appendChild(buttonNode);
  </script>
</body>
</html>
Output :

Hello world This is Text inside div.


Next Topic :