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).
jQuery prepend() Method
The jQuery prepend() method inserts content at the beginning of the selected elements.
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
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.
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
Try it Yourself »