JavaScript insertBefore
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);
Code language: CSS (css)
In this method:
- The
newNode
is the new node to be inserted. - The
existingNode
is the node before which the new node is inserted. If theexistingNode
isnull
, theinsertBefore()
inserts thenewNode
at 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);
}
Code language: JavaScript (javascript)
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>
Code language: HTML, XML (xml)
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);
Code language: JavaScript (javascript)
How it works.
- First, get the
menu
element 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
menu
element using theinsertBefore()
method.
Put it all together.
<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>
Code language: HTML, XML (xml)
Summary
- Use the
parentNode.insertBefore()
to insert a new node before an existing node as a child node of a parent node.