TExcelTAD
Home › jQuery › jQuery Add Elements

jQuery Add Elements

jQuery makes it easy to create new content and put it exactly where you want it: inside an element (at the start or end) or outside it (before or after).

The four insertion methods

Method Inserts content…
.append(content) Inside, at the end
.prepend(content) Inside, at the start
.after(content) Outside, after the element (as the next sibling)
.before(content) Outside, before the element (as the previous sibling)
text
        .before()
<ul>
        .prepend()
  <li>existing</li>
        .append()
</ul>
        .after()
html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; font-size: 14px; }
    #list { border: 2px solid #0769ad; padding: 6px 6px 6px 26px; width: 220px; }
    .outside { color: #c0392b; }
  </style>
</head>
<body>
  <button id="a">append</button>
  <button id="p">prepend</button>
  <button id="af">after</button>
  <button id="bf">before</button>
  <ul id="list">
    <li>existing item</li>
  </ul>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    let n = 0;
    $("#a").on("click", () => $("#list").append("<li>appended " + (++n) + "</li>"));
    $("#p").on("click", () => $("#list").prepend("<li>prepended " + (++n) + "</li>"));
    $("#af").on("click", () => $("#list").after("<p class='outside'>after the list " + (++n) + "</p>"));
    $("#bf").on("click", () => $("#list").before("<p class='outside'>before the list " + (++n) + "</p>"));
    $("button").on("click", () => console.log("li count:", $("#list li").length, "| p count:", $("p").length));
  </script>
</body>
</html>

The red paragraphs land outside the bordered list, the list items inside it.

Ways to create content

The content argument can be several things:

Content Example
HTML string .append("<li>New</li>")
jQuery object .append($("<li>").text(name))
DOM element .append(document.createElement("li"))
Several arguments .append(a, b, c) — all inserted in order
A function .append(function (i, oldHtml) { return "…"; })

The safest and most flexible pattern is to build elements with jQuery, then set text and attributes with methods:

js
const $link = $("<a>", {
  href: "/profile",
  text: userName,          // escaped, safe
  class: "user-link"
});
$("#nav").append($link);

Passing an object as the second argument to $("<tag>", {...}) sets attributes, and special keys such as text, html, css and event names (click) call the matching jQuery methods.

Building a list from data

html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    table { border-collapse: collapse; }
    th, td { border: 1px solid #ccc; padding: 4px 10px; text-align: left; }
    th { background: #0769ad; color: #fff; }
  </style>
</head>
<body>
  <table id="t"><tr><th>Product</th><th>Price</th></tr></table>
  <button id="more">Add a row</button>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    const products = [
      { name: "Espresso Beans", price: 24.5 },
      { name: "Green Tea", price: 9 },
      { name: "Oat Milk <1L>", price: 3.2 }      // the < > will be shown safely
    ];

    function row(p) {
      return $("<tr>").append(
        $("<td>").text(p.name),
        $("<td>").text("
quot; + p.price.toFixed(2)) ); } // build all rows first, then insert once (faster than many separate appends) $("#t").append(products.map(row)); $("#more").on("click", function () { const $r = row({ name: "Mystery item", price: 1 + $("#t tr").length }); $r.hide(); $("#t").append($r); $r.fadeIn(); console.log("rows:", $("#t tr").length - 1); }); </script> </body> </html>

.append() accepts an array of jQuery objects or elements, so products.map(row) inserts all rows in one DOM operation.

The reversed forms: appendTo, prependTo, insertAfter, insertBefore

Each method has a twin where the content comes first and the target is the argument. These return the new content, which is handy for chaining on it:

Target first Content first
$(target).append(content) $(content).appendTo(target)
$(target).prepend(content) $(content).prependTo(target)
$(target).after(content) $(content).insertAfter(target)
$(target).before(content) $(content).insertBefore(target)
html · try it yourself
<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; }
    .msg { padding: 6px 10px; margin: 4px 0; border-radius: 6px; background: #eef5fb; width: 240px; }
    .mine { background: #d4edda; margin-left: 40px; }
  </style>
</head>
<body>
  <div id="chat"><div class="msg">Hi! How can I help?</div></div>
  <input id="text" placeholder="Type a message"> <button id="send">Send</button>

  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script>
    $("#send").on("click", function () {
      const text = $("#text").val().trim();
      if (!text) return;
      $("<div class='msg mine'>")
        .text(text)
        .appendTo("#chat")      // returns the new div…
        .hide()
        .slideDown(150);        // …so we can animate it
      $("#text").val("").trigger("focus");
      console.log("messages:", $("#chat .msg").length);
    });
  </script>
</body>
</html>

Moving existing elements

If the content is an element that is already on the page, insertion methods move it rather than copy it. To duplicate it, use .clone() first:

js
$("#favorites").append($("#item-3"));          // moves #item-3
$("#favorites").append($("#item-3").clone());  // copies it

Note: If the target matches several elements, jQuery clones the content for every target except the last. Avoid duplicate ids when doing this.

Test yourself

Which method inserts content inside an element, before its first child?

  1. .before()
  2. .prepend()
  3. .append()
  4. .insertBefore()

What does $("<li>").text("x").appendTo("#list") return?

  1. #list
  2. The new <li>
  3. undefined
  4. The text "x"

$("#b").append($("#item")) — #item is already elsewhere on the page. What happens?

  1. It is copied into #b
  2. It is moved into #b
  3. An error is thrown
  4. Nothing happens