HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery Add Elements

Adding new content to your website dynamically is one of the most exciting parts of jQuery. Whether you're adding a new comment to a list, a new row to a table, or a loading message, jQuery provides four methods that let you insert content with pinpoint accuracy.


The Four Insertion Methods

There are four methods used to add new content. The difference between them is **where** they place the content relative to the target element.

before() — outside top prepend() — inside top Target Element append() — inside bottom after() — outside bottom
Method Where it adds content...
append() At the **end** of the selected elements (inside).
prepend() At the **beginning** of the selected elements (inside).
after() **After** the selected elements (outside).
before() **Before** the selected elements (outside).

Examples of Simple Insertion

$("p").append(" <b>Appended text</b>.");
$("p").prepend("<b>Prepended text</b>: ");

$("img").after("<p>This text comes AFTER the image.</p>");
$("img").before("<p>This text comes BEFORE the image.</p>");

How to Create New Elements

Before adding an element, you need to create it. There are three common ways to create new elements in jQuery:

// 1. Using an HTML string
var txt1 = "<p>Text created with HTML.</p>";

// 2. Using a jQuery object
var txt2 = $("<p></p>").text("Text created with jQuery.");

// 3. Using pure JavaScript DOM nodes
var txt3 = document.createElement("p");
txt3.innerHTML = "Text created with DOM.";

// Finally, add them to the page
$("body").append(txt1, txt2, txt3);
Multi-Add: You can pass multiple arguments to these methods (as shown above) to insert several new pieces of content at once.

Practical Use Case: To-Do List

Here is how you would add a new item to a list when a button is clicked.

$("#addBtn").click(function() {
    var itemValue = $("#inputArea").val();
    if (itemValue != "") {
        $("ul").append("<li>" + itemValue + "</li>");
        $("#inputArea").val(""); // Clear input
    }
});
Pro Tip: Use append() or prepend() for lists, sub-menus, and message logs. Use before() and after() for inserting separators, advertisements, or informational blocks.

Key Points to Remember

  • Inside vs. Outside: append/prepend go inside the tag; after/before go around the tag.
  • You can insert **HTML strings**, **jQuery objects**, or **DOM nodes**.
  • All methods support inserting **multiple** items in one call.
  • Appending content is much faster than overwriting the entire .html() content.
  • Dynamically added elements may require event delegation (using .on()) to handle clicks.