To insert a text or an element before an element, we can use the before()
method in the element object in JavaScript.
Let's say we have a HTML structure like this with a div
tag and 2 paragraph
tags inside it,
<div>
<p id="para1">I'm paragraph 1</p>
<p id="para2">I'm paragraph 2</p>
</div>
What if we want to insert a text or another element before the para1
paragraph tag? Well, Don't worry, we can use the before()
method of para1
paragraph tag to insert an element or a text.
So first, let's get the reference to the para1
paragraph tag like this,
// get reference to para1 paragraph tag
const para1 = document.querySelector("#para1");
Now let's use the before()
method in the para1
element and pass another span
element as an argument to the before()
method.
// get reference to para1 paragraph tag
const para1 = document.querySelector("#para1");
// create a span element
const span = document.createElement("span");
span.innerHTML = "I'm a span tag";
// use the before() method in the para1 tag
// to add the span tag before the para1 paragraph
// element
para1.before(span);
We can also add text content using the before()
method.
// get reference to para1 paragraph tag
const para1 = document.querySelector("#para1");
// create a span element
const span = document.createElement("span");
span.innerHTML = "I'm a span tag";
// use the before() method in the para1 tag
// to add the span tag before the para1 paragraph
// element
para1.before(span);
para1.before("I'm just a text");
Now the output looks like this,
<!--
I'm a span tag I'm just a text
I'm paragraph 1
I'm paragraph 2
-->
See this example live in JSBin.