Javascript Reference - HTML DOM insertBefore Method








The insertBefore() method inserts a node as a child before an existing specified child.

Browser Support

insertBefore Yes Yes Yes Yes Yes

Syntax

node.insertBefore(newnode,existingnode)

Parameters

Parameter Type Description
newnode Node object Required. The node object to insert
existingnode Node object Optional. The child node before the new added node. If empty, the insertBefore method adds the newnode to the end.




Return Value

It returns the node inserted as Node object type.

Example

The following code shows how to insert an item into a list.


<!DOCTYPE html>
<html>
<body>
<ul id="myList"><li>A</li><li>B</li></ul>
<button onclick="myFunction()">test</button>
<script>
function myFunction()<!--from  w w w  .  j a  va 2s .  c o m-->
{
    var newItem=document.createElement("LI")
    var textnode=document.createTextNode("C")
    newItem.appendChild(textnode)
    
    var list=document.getElementById("myList")
    list.insertBefore(newItem,list.childNodes[0]);
}
</script>
</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to move a list item from one list to another.


<!DOCTYPE html>
<html>
<body>
<!--from ww  w  .  j a  v  a2  s .  c  o m-->
<ul id="myList1"><li>A</li><li>C</li></ul>
<ul id="myList2"><li>B</li><li>D</li></ul>
<button onclick="myFunction()">test</button>
<script>
function myFunction()
{
    var node=document.getElementById("myList2").lastChild;
    var list=document.getElementById("myList1");
    list.insertBefore(node,list.childNodes[0]);
}
</script>

</body>
</html>

The code above is rendered as follows: