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 content at the end of the selected element
- Prepend ()-Inserts 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 element with HTML
var txt2=$ ("<p></p>"). Text ("text."); Create with JQuery
var txt3=document.createelement ("P"); Create with DOM
Txt3.innerhtml= "Text.";
$ ("P"). Append (TXT1,TXT2,TXT3); Append the new elements
}
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 ("Some text after");
$ ("img"). Before ("Some text before");
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>"; Create element with HTML
var txt2=$ ("<i></i>"). Text ("Love"); Create with JQuery
var txt3=document.createelement ("Big"); Create with DOM
Txt3.innerhtml= "jquery!";
$ ("img"). After (TXT1,TXT2,TXT3); Insert new elements after img
}
Try it»
JQuery add Element