jQuery - Add Elements


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


Add New HTML Content

We will learn the four jQuery methods 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 inserts content at the end of the selected elements (still inside the element).

Example

$("p").append("Append text");

Try it Yourself »


jQuery prepend() Method

The jQuery prepend() method inserts content at the beginning of the selected elements.

Example

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

Try it Yourself »


Add Several New Elements via append() and prepend() Methods

In the examples above, we only inserted text/HTML at the beginning/end of the selected elements.

However, the append() and prepend() methods can accept an unlimited number of new elements via parameters. The text/HTML can be generated via jQuery (as in the examples above), or via JavaScript code and DOM elements.

In the following example, we create several new elements. These elements can be created via text/HTML, jQuery, or JavaScript/DOM. Then we insert these new elements into the text using the append() method (valid for prepend() as well):

Example

function appendText(){ var txt1="<p>Text-1.</p>"; //Create text using HTML tags var txt2=$("<p></p>").text("Text-2."); //Create text using jQuery var txt3=document.createElement("p"); txt3.innerHTML="Text-3."; //Create text using DOM text with DOM $("body").append(txt1,txt2,txt3); //Append new elements }

Try it Yourself »


jQuery after() and before() Methods

The jQuery after() method inserts content after the selected elements.

The jQuery before() method inserts content before the selected elements.

Example

$("img").after("Add text after"); $("img").before("Add text before");

Try it Yourself »


Add Several New Elements via after() and before() Methods

The after() and before() methods can accept an unlimited number of new elements via parameters. New elements can be created via text/HTML, jQuery, or JavaScript/DOM.

In the following example, we create several new elements. These elements can be created via text/HTML, jQuery, or JavaScript/DOM. Then we insert these new elements into the text using the after() method (valid for before() as well):

Example

function afterText() { var txt1="<b>I </b>"; //Create elements using HTML var txt2=$("<i></i>").text("love "); //Create elements using jQuery var txt3=document.createElement("big"); //Create elements using DOM txt3.innerHTML="jQuery!"; $("img").after(txt1,txt2,txt3); //Add text after the image }

Try it Yourself »
Other Extensions