References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript prepend() method

Method JavaScript All modern browsers Updated
Quick answer

The prepend() method adds one or more nodes or text strings to the start of an element's children. list.prepend(newItem) puts newItem first. It's the front-insert counterpart of append(), accepts multiple arguments and plain strings, and replaces the older insertBefore() for this job.

Overview

prepend() inserts content at the beginning of an element, inside it — the mirror image of append(), which adds to the end. feed.prepend(newPost) puts the new post at the top, exactly what you want for a newest-first list, a new chat message, or a freshly added notification.

Like append(), it's flexible: it takes multiple arguments at once, and those can be strings as well as nodes. Strings are inserted as plain text (not parsed as HTML), so it's safe with user input — unlike innerHTML. It returns undefined.

It replaced the clumsier old idiom parent.insertBefore(node, parent.firstChild), which needed a reference to the first child. The related insert methods round out the set: append() for the end, before()/after() for outside the element. For building many nodes efficiently, assemble them in a DocumentFragment first.

Syntax

parent.prepend(node)
parent.prepend(node1, node2, "text")  // multiple, mixed

const li = document.createElement("li");
list.prepend(li);   // li becomes the first child

Parameters

The prepend() method accepts the following parameters.

Parameter Description
nodes/strings One or more nodes or strings to add at the start. Strings are inserted as plain text (not HTML).

Example

Live example
<ul id="feed" style="font:15px system-ui">
  <li>Older item</li>
</ul>
<button onclick="addNewest()" style="font:14px system-ui;margin-top:8px">Add newest on top</button>
<script>
  let n = 0;
  function addNewest() {
    const li = document.createElement('li');
    li.textContent = 'Newest item ' + (++n);
    document.getElementById('feed').prepend(li);
  }
</script>

Best practices

  • Use prepend() for newest-first lists and inserting at the top.
  • Pass strings for text — inserted safely, not parsed as HTML.
  • Use append() for the end, before()/after() for outside the element.
  • It replaces the older insertBefore(node, firstChild) pattern.

Frequently asked questions

What does prepend() do?
It adds nodes or text to the start of an element's children, making them the first content inside.
What is the difference between prepend() and append()?
prepend() inserts at the start; append() inserts at the end. Both accept multiple nodes and strings.
How do I add an element to the top of a list?
Use list.prepend(element), which makes it the first child.
Is prepend() safe with user text?
Yes — strings are inserted as plain text, not parsed as HTML, so they can't inject scripts.