Element insertBefore Method - Javascript DOM

Javascript examples for DOM:Element insertBefore

Description

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

Parameter Values

ParameterTypeDescription
newnode Node object Required. The node object you want to insert
existingnode Node object Optional. The child node you want to insert the new node before. If not specified, the node will be inserted at the end

Return Value:

A Node Object, representing the inserted node

The following code shows how to Insert a new <li> element before the first child element of an <ul> element:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<ul id="myList1"><li>Coffee</li><li>Tea</li></ul>

<ul id="myList2"><li>Water</li><li>Milk</li></ul>

<p>Click the button to move an item from one list to another</p>

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {//from   ww w .  j  a  va  2 s  .c  om
    var node = document.getElementById("myList2").lastChild;
    var list = document.getElementById("myList1");
    list.insertBefore(node, list.childNodes[0]);
}
</script>

</body>
</html>

Related Tutorials