How to Prepend Content Using jQuery

This guide demonstrates how to insert content at the beginning of selected elements using jQuery. You will learn the syntax and practical implementations of the two primary methods used for this task: .prepend() and .prependTo(). By the end of this guide, you will be able to efficiently add text, HTML markup, and DOM elements as the first child of any container.

Using the .prepend() Method

The .prepend() method inserts the specified content as the very first child inside each matching target element.

Syntax

$(selector).prepend(content1 [, contentN]);

Example: Adding HTML to a Container

Suppose you have an unordered list:

<ul id="my-list">
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

You can insert an item at the beginning of the list like this:

$("#my-list").prepend("<li>Item 1</li>");

Result:

<ul id="my-list">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

Using the .prependTo() Method

The .prependTo() method performs the same functional task as .prepend(), but the syntax is reversed. With .prependTo(), the content to be inserted comes first, followed by the target selector.

Syntax

$(content).prependTo(target);

Example: Moving or Inserting Elements

Using the same list:

$("<li>Item 0</li>").prependTo("#my-list");

This method is especially useful when chaining operations onto the newly created element before inserting it.


Prepending Multiple Elements or Types

Both methods accept various content types, including HTML strings, DOM elements, and jQuery objects. You can also pass multiple arguments into .prepend() simultaneously:

const newSpan = document.createElement("span");
newSpan.textContent = "Notice: ";

const strongText = $("<strong>Important! </strong>");

$("#container").prepend(newSpan, strongText, "Please read carefully.");

This adds the DOM element, the jQuery object, and the raw text node into #container in the exact order they are listed.