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.
  <ul id="list"><li>First List</li><li>Second List</li></ul>
  <button onclick="myfunc()">Click Here</button>
    function myfunc() {
      // creating a li element
      var listNode = document.createElement('li');
      var nodeText = document.createTextNode('Hello world This New List.');
      // inserting list node 
      var elem = document.getElementById('list');
      elem.insertBefore(listNode, elem.childNodes[0]);
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 :