Append and Prepend

Insert new content inside elements, at the end or the start.

Syntax$(parent).append(content); $(parent).prepend(content);

These methods add content inside the selected elements:

  • .append() — add to the end of the contents.
  • .prepend() — add to the start of the contents.

You can pass an HTML string, a DOM element, or a jQuery object.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A todo app calls .append('<li>New task</li>') on the list each time the user submits the form.
  • A notification system .prepend()s new alerts at the top of the notice stack so the latest appears first.
  • A dynamic table builds rows with .append() after receiving AJAX JSON, adding each record as a <tr>.

More examples

Append a list item on click

.append() inserts new HTML as the last child inside the matched element, growing the list at the bottom.

Example · html
<ul id="tasks"><li>Buy milk</li></ul>
<button id="add">Add task</button>
<script>
$(function () {
  var n = 1;
  $("#add").click(function () {
    n++;
    $("#tasks").append("<li>New task " + n + "</li>");
  });
});
</script>

Prepend newest alert to a stack

.prepend() inserts at the top of the container so the newest notification always appears first.

Example · html
<div id="notices"></div>
<button id="notify">New notification</button>
<script>
$(function () {
  var i = 0;
  $("#notify").click(function () {
    i++;
    $("#notices").prepend(
      "<p style='background:#f39c12;padding:6px;margin:4px 0'>Alert #" + i + "</p>"
    );
  });
});
</script>

Append HTML element object

Creating a jQuery element object first lets you style and configure it before appending, avoiding inline HTML strings.

Example · html
<ul id="list"></ul>
<button id="addEl">Add element</button>
<script>
$(function () {
  $("#addEl").click(function () {
    var $li = $("<li>").text("Item added via element").css("color", "steelblue");
    $("#list").append($li);
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.
Append and Prepend — jQuery | SoundsCode