Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 56 ยท Manipulating the DOM

Inserting Content

Insert and create elements with jQuery: append, prepend, before, after, the appendTo family, moving versus cloning, and building lists from arrays safely.

Reading and changing text is only half of working with a page. Real interfaces add new rows to a table, drop a notice above a form, and build whole lists from data. jQuery has a small, consistent family of methods for this. Once you see that they differ only in where the new content goes and which side of the sentence the target is on, there is very little to memorize.

Four places to insert

.append() Inside the target, at the end.
.prepend() Inside the target, at the start.
.before() Outside, as the previous sibling.
.after() Outside, as the next sibling.
1 / 2

append, prepend, before and after

Imagine this list:

HTML
<ul id="menu">
  <li>Home</li>
  <li>Docs</li>
</ul>

Each method puts a new <li> (or any content) in a different spot:

JavaScript
$("#menu").append("<li>End</li>");    // inside #menu, after Docs
$("#menu").prepend("<li>Start</li>"); // inside #menu, before Home
$("#menu li:first").before("<li>Above Home</li>"); // sibling, outside the first li
$("#menu li:last").after("<li>Below last</li>");   // sibling, outside the last li

The content you pass can be an HTML string, a DOM element, a jQuery object, an array of those, or several arguments in a row. .append("<b>A</b>", "<i>B</i>") inserts both. You can even pass a function that returns the content for each target.

If the target collection holds several elements, the content is inserted into each one. jQuery clones it as needed, so every target gets its own copy.

Four insertion points

The To family: appendTo, prependTo, insertBefore, insertAfter

Each method has a mirror image where the content comes first:

Target first Content first
$(target).append(content) $(content).appendTo(target)
$(target).prepend(content) $(content).prependTo(target)
$(target).before(content) $(content).insertBefore(target)
$(target).after(content) $(content).insertAfter(target)

The result on the page is identical. The difference is the return value, which matters for chaining: .append() returns the target, while .appendTo() returns the content you just inserted. So when you create something new and want to keep working on it, the To form reads better:

JavaScript
$("<li>").text("Pricing").addClass("new").appendTo("#menu");

Moving versus cloning

An element can live in only one place. If you insert an element that is already in the document, jQuery moves it; it does not copy it.

JavaScript
$("#footer-note").appendTo("#sidebar");   // moved, no longer in the footer

When the target has several elements, the original goes into the last one and clones go into the others. To keep the original where it is and insert a copy, clone it first:

JavaScript
$("#footer-note").clone().appendTo("#sidebar");

Be careful with .clone() and id attributes: a clone has the same id, which makes the document invalid. Remove or change the id on the copy. More on cloning, including copying event handlers, is in Removing, Replacing, Wrapping.

Creating elements

You can pass an HTML string to $() to create elements, but there is a nicer and safer form: pass a single tag and an object of settings.

JavaScript
var $link = $("<a>", {
  href: "/docs",
  text: "Read the docs",
  class: "button",
  "data-source": "menu",
  click: function (e) {
    e.preventDefault();
    console.log("clicked");
  }
});

The object accepts attributes, jQuery methods such as text, html, css, val, data and width, and event names like click. Because text is used as plain text, this style is safe for values that come from users. Contrast that with building a string by hand, such as "<li>" + userInput + "</li>", where a value like <img src=x onerror=alert(1)> becomes live HTML. The rule of thumb: user data goes in through text, .text() or properties, never through string concatenation into HTML.

Building lists from arrays

The usual pattern is to turn an array of data into an array of elements and insert them in one go. Inserting once instead of in a loop is also faster, because the browser updates the page a single time.

JavaScript
var names = ["Ana", "Ben", "Chloe"];
var $items = $.map(names, function (name) {
  return $("<li>", { text: name });
});
$("#people").append($items);

Here $.map returns an array of jQuery objects, and jQuery flattens it for .append(). When you build rows with several cells, create the row first and append the cells to it:

JavaScript
var $row = $("<tr>");
$("<td>", { text: item.name }).appendTo($row);
$("<td>", { text: item.price.toFixed(2) }).appendTo($row);
$("#table tbody").append($row);
Create elements from data and move one

Notice that the "Chair" row shows the literal text <b>Pro</b>: because the name went in through text, it stayed text. The move button flips the same element between zones, while the copy button leaves the original alone and adds a clone without an id.

Creating many elements efficiently

Creating elements is cheap; inserting them one at a time into the live document is not, because the browser may recalculate layout after each insertion. When you build a long list, create everything first and insert once.

JavaScript
// Slow pattern: 500 separate DOM insertions
for (var i = 0; i < 500; i++) {
  $("#list").append("<li>Item " + i + "</li>");
}

// Better: build in memory, insert once
var items = [];
for (var j = 0; j < 500; j++) {
  items.push($("<li>").text("Item " + j));   // detached elements
}
$("#list").append(items);                    // one insertion

A third option is to build one HTML string from trusted data and insert it once with .html(). Prefer the array form with user data, because .text() keeps it safe. Both approaches below give the same result; the difference is how many times the live document is touched.

Insert once instead of 500 times

For very large lists, a DocumentFragment or innerHTML is faster still, and the best answer for huge tables is not to render rows that are off-screen at all.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call puts a new <li> as the first child inside #menu?

    prepend inserts inside the target at the start. append inserts at the end, and before and after insert outside the target.
  2. 2. What is the main difference between $("ul").append(li) and $(li).appendTo("ul")?

    Both produce the same DOM. The return value differs, which affects what you can chain next.
  3. 3. What happens when you append an element that is already in the document to a different parent?

    An element can only exist in one place, so jQuery moves it. Call .clone() first if you want a copy.
  4. 4. Why is $("<li>", { text: userName }) safer than $("<li>" + userName + "</li>")?

    String concatenation lets a value contain tags that the browser will parse. The text option never parses HTML.

Summary

  • .append() and .prepend() insert inside a target; .before() and .after() insert beside it.
  • .appendTo(), .prependTo(), .insertBefore() and .insertAfter() put the content first and return the inserted content.
  • Inserting an existing element moves it; use .clone() to copy, and change duplicated id values.
  • $("<tag>", { props }) creates an element with attributes, text and handlers in one step.
  • Pass user-provided values through text, not through string concatenation.
  • Build arrays of elements with $.map and insert them with one call.

Next, learn how to take content away or wrap it in Removing, Replacing, Wrapping.