Summary: in this tutorial, you’ll learn about the JavaScript prepend()
method that inserts Node
objects or DOMString
objects before the first child of a parent node.
Introduction to JavaScript prepend() method
The prepend()
method inserts a set of Node
objects or DOMString
objects before the first child of a parent node:
parentNode.prepend(...nodes);
parentNode.prepend(...DOMStrings);
Code language: JavaScript (javascript)
The prepend()
method inserts DOMString
objects as Text
nodes. Note that a DOMString
is a UTF-16 string that directly maps to a string.
The prepend()
method returns undefined
.
JavaScript prepend() method examples
Let’s take some examples of using the prepend()
method.
1) Using the prepend() method to prepend an element example
Let’s say you have the following <ul>
element:
<ul id="app">
<li>HTML</li>
</ul>
Code language: HTML, XML (xml)
This example shows how to create a list of li
elements and prepend them to the ul
element:
let app = document.querySelector('#app');
let langs = ['CSS','JavaScript','TypeScript'];
let nodes = langs.map(lang => {
let li = document.createElement('li');
li.textContent = lang;
return li;
});
app.prepend(...nodes);
Code language: JavaScript (javascript)
Output HTML:
<ul id="app">
<li>CSS</li>
<li>JavaScript</li>
<li>TypeScript</li>
<li>HTML</li>
</ul>
Code language: HTML, XML (xml)
How it works:
- First, select the
ul
element by its id by using thequerySelector()
method. - Second, declare an array of strings.
- Third, for each element in an array, create a new
li
element with thetextContent
is assigned to the array element. - Finally, prepend the
li
elements to theul
parent element by using theprepend()
method.
2) Using the prepend() method to prepend text to an element example
Suppose that you have the following element:
<div id="app"></div>
Code language: HTML, XML (xml)
The following shows how to use the prepend()
method to prepend a text to the above <div>
element:
let app = document.querySelector('#app');
app.prepend('prepend() Text Demo');
console.log(app.textContent);
Code language: JavaScript (javascript)
Output HTML:
<div id="app">prepend() Text Demo</div>
Code language: HTML, XML (xml)
Summary
- Use the
parentNode.prepend()
method to prepend a list ofNode
objects orDOMString
objects before the first child node of the parent node.