Javascript examples for DOM:Element insertBefore
The insertBefore() method inserts a node before an existing child.
Parameter | Type | Description |
---|---|---|
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 |
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:
<!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>