May 07, 2021 jQuery
5. Add a number of new elements through the append() and prepend() methods
6. jQuery after() and before() methods
8.. Add several new elements through the after() and before() methods
jQuery makes it easy to add new elements/content.
We'll learn four jQuery methods for adding new content:
The jQuery append() method inserts content at the end of the selected element.
The jQuery prepend() method inserts content at the beginning of the selected element.
In the example above, we only insert 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 generate text/HTML (as in the example above) with jQuery, or through JavaScript code and DOM elements.
In the following example, we create several new elements. T hese elements can be created by text/HTML, jQuery, or JavaScript/DOM. Then we append these new elements to the text via the append() method (as well as prepend():
The jQuery after() method inserts content after the selected element.
The jQuery before() method inserts content before the selected element.
The after() and before() methods can receive an unlimited number of new elements through parameters. New elements can be created by text/HTML, jQuery, or JavaScript/DOM.
In the following example, we create several new elements. T hese elements can be created by text/HTML, jQuery, or JavaScript/DOM. Then we insert these new elements into the text by the after() method (which is equally valid for before():
Tip: In jQuery, append/prepend is embedded inside the selection element, whileafter/before is appended outside the element.