With JQuery, it's easy to add new elements/content.
Add a new HTML content
We'll learn the four jQuery methods for adding new content:
- Append ()-Inserts the specified content at the end of the selected element
- Prepend ()-Inserts the specified content at the beginning of the selected element
- After ()-Inserts the content after the selected element
- Before ()-insert content before selected element
JQuery Append () method
The JQuery append () method inserts the content at the end of the selected element.
Instance $ ("P"). Append ("Some appended text.");
Try it?
JQuery prepend () method
The JQuery prepend () method inserts content at the beginning of the selected element.
Instance $ ("P"). Prepend ("Some prepended text.");
Try it?
Adding several new elements through the Append () and prepend () methods
In the example above, we only insert the text/html at the beginning/end of the selected element.
However, the Append () and prepend () methods can receive an unlimited number of new elements through parameters. You can use JQuery to generate text/html (as in the example above), or through JavaScript code and DOM elements.
In the following example, we create a number of new elements. These elements can be created by text/html, JQuery, or javascript/dom. We then append these new elements to the text (as valid for prepend () using the Append () method:
instance function AppendText ()
{
var txt1= "<p>Text.</p>"; Create text using HTML tags
var txt2=$ ("<p></p>"). Text ("text."); Create text using JQuery
var txt3=document.createelement ("P");
Txt3.innerhtml= "text. "; Using the DOM to create text with DOM
$ ("P"). Append (TXT1,TXT2,TXT3); Append new Element
}
Try it?
JQuery after () and before () methods
The JQuery after () method inserts content after the selected element.
The JQuery before () method inserts content before the selected element.
Instance $ ("img"). After ("Add text after");
$ ("img"). Before ("Add text in front");
Try it?
Adding several new elements through the After () and before () methods
The After () and before () methods can receive an unlimited number of new elements through parameters. You can create new elements through text/html, JQuery, or javascript/dom.
In the following example, we create several new elements. These elements can be created by text/html, JQuery, or javascript/dom. We then use the After () method to insert these new elements into the text (as valid for Before ()):
instance function Aftertext ()
{
var txt1= "<b>i </b>"; Creating Elements with HTML
var txt2=$ ("<i></i>"). Text ("Love"); Creating Elements with JQuery
var txt3=document.createelement ("Big"); Creating elements using the DOM
Txt3.innerhtml= "jquery!";
$ ("img"). After (TXT1,TXT2,TXT3); Add text after a picture
}
Try it?
tip: in jquery, Append/prepend is embedded inside the selection element, and After/before is appended outside the element.
JQuery add Element