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);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>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);Output HTML:
<ul id="app">
<li>CSS</li>
<li>JavaScript</li>
<li>TypeScript</li>
<li>HTML</li>
</ul>How it works:
- First, select the
ulelement by its id by using thequerySelector()method. - Second, declare an array of strings.
- Third, for each element in an array, create a new
lielement with thetextContentis assigned to the array element. - Finally, prepend the
lielements to theulparent 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>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);Output HTML:
<div id="app">prepend() Text Demo</div>Summary #
- Use the
parentNode.prepend()method to prepend a list ofNodeobjects orDOMStringobjects before the first child node of the parent node.
Quiz #
Understanding prepend() Method
Thank you for your feedback!