jQuery Add

jQuery Add Elements

jQuery simplifies adding entirely new elements and content to an existing HTML page.

This allows you to dynamically build websites based on user interaction or data loading.


Methods to Add New Content

We will focus on four primary jQuery methods used to add new HTML content:


The append() Method

The append() method places your new content inside the selected element, at the very end.

If you append to a list (<ul>), it will become the final list item.

Append Example:

$("p").append(" Appended text.");
$("ol").append("
  • Appended item
  • ");

    The prepend() Method

    The prepend() method places your new content inside the selected element, at the very beginning.

    If you prepend to a paragraph, it will appear before the existing text inside that paragraph.

    Prepend Example:

    $("p").prepend("Prepended text. ");
    

    The after() and before() Methods

    The after() method inserts content completely outside and after the selected element.

    The before() method inserts content completely outside and before the selected element.

    After and Before Example:

    $("img").before("Before image");
    $("img").after("After image");
    

    Adding Multiple New Elements

    All four methods (append, prepend, before, after) can take an infinite number of new elements as parameters.

    You can create these elements using raw HTML, jQuery, or vanilla JavaScript DOM methods.

    Multiple Elements Example:

    function appendText() {
      var txt1 = "<p>Text.</p>";               // Create element with HTML  
      var txt2 = $("<p></p>").text("Text.");   // Create with jQuery
      var txt3 = document.createElement("p"); // Create with DOM
      txt3.innerHTML = "Text.";
      $("body").append(txt1, txt2, txt3);     // Append all 3
    }
    

    Exercise 1 of 2

    ?

    Which method inserts content INSIDE a selected element, placing it at the very end?

    Exercise 2 of 2

    ?

    Is it possible to pass multiple strings or elements into the append() method at the same time?