prepend method
The prepend
method allows you
to insert another element at the
beginning of an element. The method
takes an element as a parameter,
usually created with
createElement
,
or a string. You can add several
elements or strings at once by listing
them separated by commas.
Syntax
parent.prepend(element or string);
Example
Let's create a paragraph, set its text
and place it on a page at the beginning
of the #parent
block:
<div id="parent">
<p>1</p>
<p>2</p>
<p>3</p>
</div>
let parent = document.querySelector('#parent');
let p = document.createElement('p');
p.textContent = '!';
parent.prepend(p);
The code execution result:
<div id="parent">
<p>!</p>
<p>1</p>
<p>2</p>
<p>3</p>
</div>
Example
Let's put several paragraphs at once
at the beginning of the #parent
block:
<div id="parent">
<p>1</p>
<p>2</p>
<p>3</p>
</div>
let parent = document.querySelector('#parent');
let p1 = document.createElement('p');
p1.textContent = 'a';
let p2 = document.createElement('p');
p2.textContent = 'b';
parent.prepend(p1, p2);
The code execution result:
<div id="parent">
<p>b</p>
<p>a</p>
<p>1</p>
<p>2</p>
<p>3</p>
</div>
Example
Let's use a string as a method parameter:
<div id="parent">
<p>1</p>
<p>2</p>
<p>3</p>
</div>
let parent = document.querySelector('#parent');
parent.prepend('!');
The code execution result:
<div id="parent">
!
<p>1</p>
<p>2</p>
<p>3</p>
</div>
See also
-
the
append
method
that inserts elements at the end -
the
appendChild
method
that inserts elements at the end -
the
insertBefore
method
that inserts an element before an element -
the
insertAdjacentElement
method
that inserts an element at the given location -
the
insertAdjacentHTML
,
that inserts tags at the given location