JavaScript’s Element.prepend()
method inserts a set of Node
or string objects before the first child of the Element
.
Syntax
Element.prepend(parameter1)
Element.prepend(parameter1, parameter2, /* … , */ parameterN)
Parameters
One or more Node
or string objects.
Return value
The prepend()
method does not have a return value, which means that the method implicitly returns undefined
.
Exceptions
HierarchyRequestError
DOMException
Thrown when the node cannot be inserted at the specified point in the hierarchy.
Examples
Here are some examples of using the JavaScript prepend()
method.
Prepending an element
Suppose we have the following unordered list and we would like to add more languages to the beginning of the list:
<ul id="list">
<li>Python</li>
</ul>
What should we do?
Well, we should create more li
elements and prepend them to the ul
element:
let list = document.getElementById('list');
let languages = ['JavaScript', 'C#', 'Java'];
let nodes = languages.map(language => {
let li = document.createElement('li');
li.textContent = language;
return li;
});
list.prepend(...nodes);
Now our HTML looks like this:
<ul id="list">
<li>JavaScript</li>
<li>C#</li>
<li>Java</li>
<li>Python</li>
</ul>
Here is how our HTML looks like in the browser:
- JavaScript
- C#
- Java
- Python
So, what did we do?
First we used the getElementById()
method to select the ul
element by its id
. Then we declared an array of programming languages. For each language, we created a new li
element and set the element’s textContent
. Finally, we used the spread operator (...
) to expand the array of li
elements and prepended the elements to the ul
element.
Prepending text
Now we would like to prepend some text to the first li
element in our list of programming languages. We can do that by selecting the li
element with the querySelector()
method and using the prepend()
method:
let first = document.querySelector('#list li:first-child');
first.prepend('The number one language is ');
Here is our HTML after the changes:
<ul id="list">
<li>The number one language is JavaScript</li>
<li>C#</li>
<li>Java</li>
<li>Python</li>
</ul>
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
Chrome (Android)
|
Firefox (Android)
|
Opera (Android)
|
Safari (iOS)
|
Samsung Internet
|
WebView (Android)
|
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
prepend() |
54 | 17 | 49 | 41 | 10 | 54 | 49 | 41 | 10 | 6.0 | 54 |