Episode 9 of 24

Add Content to a Web Page with jQuery

Learn how to insert new content into the page using append, prepend, before, and after.

jQuery makes it easy to add new content to your web pages dynamically.

append() — Add Inside, at the End

// Add to the end of an element
$("ul").append("<li>New item at the end</li>");

// Append to multiple elements
$(".container").append("<p>Added paragraph</p>");

prepend() — Add Inside, at the Beginning

$("ul").prepend("<li>New item at the start</li>");
$(".content").prepend("<h2>Introduction</h2>");

after() — Add Outside, After

$("h1").after("<p>This paragraph appears after the h1</p>");
$(".header").after("<nav>Navigation here</nav>");

before() — Add Outside, Before

$("h1").before("<p>This paragraph appears before the h1</p>");
$("footer").before("<hr>");

Creating Elements

// Create and configure an element
let $newCard = $("<div>")
    .addClass("card")
    .html("<h3>Title</h3><p>Description</p>")
    .css({
        padding: "1rem",
        background: "white",
        borderRadius: "8px",
        boxShadow: "0 2px 8px rgba(0,0,0,0.1)"
    });

$(".cards-container").append($newCard);

appendTo() and prependTo()

These reverse the order — content first, then target:

// Same result, different syntax
$("<li>New item</li>").appendTo("ul");
$("<li>First item</li>").prependTo("ul");

Practical Example — Adding List Items

$("#addBtn").click(function() {
    let text = $("#itemInput").val().trim();
    if (text) {
        $("<li>").text(text).appendTo("#todoList");
        $("#itemInput").val(""); // Clear input
    }
});