Javascript DOM HTML Node insertBefore Method

Introduction

Insert a new <li> element before the first child element of an <ul> element:

Click the button to insert an item to the list.

View in separate window

<!DOCTYPE html>
<html>
<body>

<ul id="myList">
  <li>CSS</li>
  <li>HTML</li>
</ul>//from w  ww.  ja v  a2s.  co m
<button onclick="myFunction()">Test</button>
<script>
function myFunction() {
  var newItem = document.createElement("LI");
  var textnode = document.createTextNode("Water");
  newItem.appendChild(textnode);

  var list = document.getElementById("myList");
  list.insertBefore(newItem, list.childNodes[0]);
}
</script>

</body>
</html>

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

insertBefore(newnode, existingnode);

Parameter Values

Parameter
Type
Description
newnode
Node object
Required. The node object to insert
existingnode

Node object Required. The child node to insert the new node before.
If set to null, the insertBefore() method will insert the newnode at the end

The insertBefore() method returns a Node Object, representing the inserted node.




PreviousNext

Related