jQuery - Adding Elements
With jQuery, it is easy to add new elements/content.
Adding New HTML Content
We will learn about four jQuery methods for adding 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("Appended text");
jQuery prepend() Method
The jQuery prepend() method inserts content at the beginning of the selected elements.
Example
$("p").prepend("Prepended text at the beginning");
Adding Multiple New Elements with 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 take an unlimited number of new elements as parameters. These can be generated by jQuery (as in the examples above), or by 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 append these new elements to the text (the same applies to prepend()):
Example
function appendText(){
var txt1="<p>Text-1.</p>"; // Create text with HTML tags
var txt2=$("<p></p>").text("Text-2."); // Create text with jQuery
var txt3=document.createElement("p");
txt3.innerHTML="Text-3."; // Create text with DOM
$("body").append(txt1,txt2,txt3); // Append new elements
}
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("Text added after");
$("img").before("Text added before");
Adding Multiple New Elements with after() and before() Methods
The after() and before() methods can take an unlimited number of new elements as parameters. These 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 (the same applies to before()):
Example
function afterText()
{
var txt1="<b>I </b>"; // Create element with HTML
var txt2=$("<i></i>").text("love "); // Create element with jQuery
var txt3=document.createElement("big"); // Create element with DOM
txt3.innerHTML="jQuery!";
$("img").after(txt1,txt2,txt3); // Add text after the image
}