insertAdjacentElement method
The insertAdjacentElement
method
allows you to insert an element anywhere
on a page. Most commonly used after
creating an element with
createElement
.
The code is inserted relative to the
target element. You can insert
before the target element
(beforeBegin
insertion method),
after it (afterEnd
insertion method),
and also at the beginning (afterBegin
insertion method) or at the end
(beforeEnd
insertion method) of
the target element.
Syntax
target element.insertAdjacentElement(insertion method, code to insert);
Example . beforeBegin
method
Let a target element be the
#target
element. We insert
a new paragraph before it:
<div id="target">
<p>elem</p>
</div>
let p = document.createElement('p');
p.textContent = '!';
let target = document.querySelector('#target');
target.insertAdjacentElement('beforeBegin', p);
The code execution result:
<p>!</p>
<div id="target">
<p>elem</p>
</div>
Example . afterEnd
method
And now we insert a new paragraph after the target element:
<div id="target">
<p>elem</p>
</div>
let p = document.createElement('p');
p.textContent = '!';
let target = document.querySelector('#target');
target.insertAdjacentElement('afterEnd', p);
The code execution result:
<div id="target">
<p>elem</p>
</div>
<p>!</p>
Example . afterBegin
method
Let's insert a new paragraph at the beginning of the target element:
<div id="target">
<p>elem</p>
</div>
let p = document.createElement('p');
p.textContent = '!';
let target = document.querySelector('#target');
target.insertAdjacentElement('afterBegin', p);
The code execution result:
<div id="target">
<p>!</p>
<p>elem</p>
</div>
Example . beforeEnd
method
Let's insert a new paragraph at the end of the target element:
<div id="target">
<p>elem</p>
</div>
let p = document.createElement('p');
p.textContent = '!';
let target = document.querySelector('#target');
target.insertAdjacentElement('beforeEnd', p);
The code execution result:
<div id="target">
<p>elem</p>
<p>!</p>
</div>
See also
-
the
insertAdjacentHTML
,
that inserts tags at the given location -
the
insertAdjacentText
method
that inserts text at the given location -
the
prepend
method
that inserts elements at the start -
the
append
method
that inserts elements at the end -
the
appendChild
method
that inserts elements at the end of a parent -
the
insertBefore
method
that inserts elements before an element