HTML DOM insertBefore() Method

The insertBefore() method is used to insert a node as a child, before an existing child. The syntax of insertBefore() is as follows :
  node.insertBefore(newnode, existingNode)
Where the newNode is the node you want to insert and existingNode is the node you want to insert the new node before.
<html>
<body>
  <ul id="list"><li>First List</li><li>Second List</li></ul>
  <button onclick="myfunc()">Click Here</button>
  <script>
    function myfunc() {
      // creating a li element
      var listNode = document.createElement('li');
      var nodeText = document.createTextNode('Hello world This New List.');
      listNode.appendChild(nodeText);
 
      // inserting list node 
      var elem = document.getElementById('list');
      elem.insertBefore(listNode, elem.childNodes[0]);
    }  
  </script>
</body>
</html>
Output :

  • First List
  • Second List

At the above example first a new <li> element is created through createElement() function and then it is inserted to <ul> list.


Next Topic :