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:
xxxxxxxxxx
1
// newNode before referenceNode
2
parentNode.insertBefore(newNode, referenceNode);
3
4
// newNode at first position in parentNode
5
parentNode.insertBefore(newNode, parentNode.firstChild);
Note:
If the given node already exists,
insertBefore()
moves it from its current position to the new one.
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
.
In this example, we will insert a new paragraph before child-2
element.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="parent">
5
<p id="child-1">This is a paragraph 1.</p>
6
<p id="child-2">This is a paragraph 2.</p>
7
</div>
8
<script>
9
10
var parent = document.querySelector("#parent");
11
var child1 = document.querySelector("#child-1");
12
var child2 = document.querySelector("#child-2");
13
14
var paragraph = document.createElement("p");
15
paragraph.innerText = 'This is new paragraph placed before child-2.';
16
17
parent.insertBefore(paragraph, child2);
18
19
</script>
20
</body>
21
</html>
In this example, we will insert a new paragraph before all child elements inside the parent
.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="parent">
5
<p id="child-1">This is a paragraph 1.</p>
6
<p id="child-2">This is a paragraph 2.</p>
7
</div>
8
<script>
9
10
var parent = document.querySelector("#parent");
11
12
var paragraph = document.createElement("p");
13
paragraph.innerText = 'This is new paragraph placed as first.';
14
15
parent.insertBefore(paragraph, parent.firstChild);
16
17
</script>
18
</body>
19
</html>