Summary: in this tutorial, you will learn how to use the JavaScript insertBefore() to insert a node before another node as a child node of a specified parent node.
Introduction to JavaScript insertBefore() method #
To insert a node before another node as a child node of a parent node, you use the parentNode.insertBefore() method:
parentNode.insertBefore(newNode, existingNode);In this method:
- The
newNodeis the new node to be inserted. - The
existingNodeis the node before which the new node is inserted. If theexistingNodeisnull, theinsertBefore()inserts thenewNodeat the end of theparentNode‘s child nodes.
The insertBefore() returns the inserted child node.
JavaScript insertBefore() helper function #
The following insertBefore() function inserts a new node before a specified node:
function insertBefore(newNode, existingNode) {
existingNode.parentNode.insertBefore(newNode, existingNode);
}JavaScript insertBefore() example #
Suppose that you have the following list of items:
<ul id="menu">
<li>Services</li>
<li>About</li>
<li>Contact</li>
</ul>The following example uses the insertBefore() method to insert a new node as the first list item:
let menu = document.getElementById('menu');
// create a new li node
let li = document.createElement('li');
li.textContent = 'Home';
// insert a new node before the first list item
menu.insertBefore(li, menu.firstElementChild);How it works.
- First, get the
menuelement using thegetElementById()method. - Second, create a new list item using the
createElement()method. - Third, insert the list item element before the first child element of the
menuelement using theinsertBefore()method.
Put it all together.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript insertBefore()</title>
</head>
<body>
<ul id="menu">
<li>Services</li>
<li>About</li>
<li>Contact</li>
</ul>
<script>
let menu = document.getElementById('menu');
// create a new li node
let li = document.createElement('li');
li.textContent = 'Home';
// insert a new node before the first list item
menu.insertBefore(li, menu.firstElementChild);
</script>
</body>
</html>Summary #
- Use the
parentNode.insertBefore()to insert a new node before an existing node as a child node of a parent node.
Thank you for your feedback!