JavaScript prepend() Method

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 ul element by its id by using the querySelector() method.
  • Second, declare an array of strings.
  • Third, for each element in an array, create a new li element with the textContent is assigned to the array element.
  • Finally, prepend the li elements to the ul parent element by using the prepend() 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 of Node objects or DOMString objects before the first child node of the parent node.

Quiz #

Quiz

Understanding prepend() Method

5 questions

Test your understanding of the prepend() method and its usage in JavaScript

Was this helpful?