insertBefore method
The insertBefore
method allows
you to insert an element before another
element. It most commonly used after
creating an element with
createElement
.
The method is applied to the parent
of the element before which the
insertion will occur.
Syntax
parent.insertBefore(element, node before which to insert);
Example
Create a paragraph and place it before the second paragraph:
<div id="parent">
<p>elem 1</p>
<p id="before">elem 2</p>
<p>elem 3</p>
</div>
let parent = document.querySelector('#parent');
let before = document.querySelector('#before');
let p = document.createElement('p');
p.textContent = '!';
parent.insertBefore(p, before);
The code execution result:
<div id="parent">
<p>elem 1</p>
<p>!</p>
<p>elem 2</p>
<p>elem 3</p>
</div>
Example
We add a paragraph to the beginning of
the #parent
element. To do this,
we insert our paragraph before the first
child of the #parent
. This child
can be found with
firstElementChild
:
<div id="parent">
<p>elem 1</p>
<p>elem 2</p>
</div>
let parent = document.querySelector('#parent');
let p = document.createElement('p');
p.textContent = '!';
parent.insertBefore(p, parent.firstElementChild);
The code execution result:
<div id="parent">
<p>!</p>
<p>elem 1</p>
<p>elem 2</p>
</div>
Example
When passing null
as the second
parameter, the insertBefore
method
works like
appendChild
.
At the same time, if the element has no
children, firstElementChild
returns
null
. Therefore, you can add to
the beginning of an element even when
it has no child elements:
<div id="parent"></div>
let parent = document.querySelector('#parent');
let p = document.createElement('p');
p.textContent = '!';
parent.insertBefore(p, parent.firstChild);
The code execution result:
<div id="parent">
<p>!</p>
</div>
See also
-
the
prepend
method
that inserts elements at the start -
the
appendChild
method
that inserts elements at the end of a parent -
the
insertAdjacentElement
method
that inserts an element at the given location -
the
insertAdjacentHTML
,
that inserts tags at the given location