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:
parentElement.insertBefore(newElement, someElement);
Hint: by using
parentElement.insertBefore(newElement, parentElement.firstChild)
we can add new element at first position.
Practical examples
Example 1 - 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>
Example 2 - 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>