EN
JavaScript - Node insertBefore() method example
0
points
In this article, I would like to present documentation of the Node.insertBefore()
method.
The method inserts a node before referenceNode
as a child of a specified parentNode
.
Quick overlook:
// newNode before referenceNode
parentNode.insertBefore(newNode, referenceNode);
// newNode at first position in parentNode
parentNode.insertBefore(newNode, parentNode.firstChild);
Note:
If the given node already exists,
insertBefore()
moves it from its current position to the new one.
1. Documentation
Syntax | parentNode.insertBefore(newNode, referenceNode) |
Parameters |
|
Result |
The method returns the added child. |
Description | The method inserts a node before referenceNode as a child of a specified parentNode . |
Note:
If the
referenceNode
isnull
, thennewNode
is inserted at the end ofparentNode
.
2. Insert before indicated element (between elements)
In this example, we will insert a new paragraph before child-2
element.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="parent">
<p id="child-1">This is a paragraph 1.</p>
<p id="child-2">This is a paragraph 2.</p>
</div>
<script>
var parent = document.querySelector("#parent");
var child1 = document.querySelector("#child-1");
var child2 = document.querySelector("#child-2");
var paragraph = document.createElement("p");
paragraph.innerText = 'This is new paragraph placed before child-2.';
parent.insertBefore(paragraph, child2);
</script>
</body>
</html>
3. Insert as first element
In this example, we will insert a new paragraph before all child elements inside the parent
.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div id="parent">
<p id="child-1">This is a paragraph 1.</p>
<p id="child-2">This is a paragraph 2.</p>
</div>
<script>
var parent = document.querySelector("#parent");
var paragraph = document.createElement("p");
paragraph.innerText = 'This is new paragraph placed as first.';
parent.insertBefore(paragraph, parent.firstChild);
</script>
</body>
</html>