jQuery - Add Elements


With jQuery, it is easy to add new elements/content.


Add New HTML Content

We will look at four jQuery methods that are used to add new content:

  • append() - Inserts content at the end of the selected elements
  • prepend() - Inserts content at the beginning of the selected elements
  • after() - Inserts content after the selected elements
  • before() - Inserts content before the selected elements

jQuery append() Method

The jQuery append() method entries content to the END of selected HTML objects.


Example
$("p").append("Some appended text.");


jQuery prepend() Method

The jQuery prepend() method incorporates content INTO the selected HTML elements.


Example
$("p").prepend("Some prepended text.");


Add Several New Elements With append() and prepend()

In both of the above examples, we only included text / HTML at the beginning / end of selected HTML objects.

However, both append() and prepend() methods can take an unlimited number of new elements as parameters. New elements can be generated with text / HTML (as we did in the examples above), with jQuery, or with JavaScript code and DOM objects.

In the following example, we create a few new elements. Elements created with text / HTML, jQuery, and JavaScript / DOM. Then add new features to the text in the form of an append() (this would work for the prepend() again):


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 the new elements
}


jQuery after() and before() Methods

The jQuery after() method inserts content AFTER selected HTML objects.

The jQuery before() method inserts content BEFORE selected HTML objects.


Example
$("img").after("Some text after");

$("img").before("Some text before");


Add Several New Elements With after() and before()

Also, both after() and before() modes can take an infinite number of new elements as parameters. New elements can be generated with text / HTML (as we did in the example above), with jQuery, or with JavaScript code and DOM objects.

In the following example, we create a few new elements. Items are created with text / HTML, jQuery, and JavaScript / DOM. Then add new items to the text via the after() method (this would work before() also):


Example
function afterText() {
  var txt1 = "<b>I </b>";                    // Create element with HTML 
  var txt2 = $("<i></i>").text("love ");     // Create with jQuery
  var txt3 = document.createElement("b");    // Create with DOM
  txt3.innerHTML = "jQuery!";
  $("img").after(txt1, txt2, txt3);          // Insert new elements after <img>
}