EN
JavaScript - insert HTML element before element
4 points
In this article, we would like to show you how to insert HTML element before the element using insertBefore
function in JavaScript.
Quick solution:
xxxxxxxxxx
1
parentElement.insertBefore(newElement, someElement);
Hint: by using
parentElement.insertBefore(newElement, parentElement.firstChild)
we can add new element at first position.
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>