Introduction to jQuery
JQuery Syntax
JQuery Effects
JQuery HTML
JQuery Traversing
jQuery provides several methods to add new HTML elements to the DOM dynamically. These methods make it super easy to insert content before, after, inside, or around existing elements.
We will look at four jQuery methods that are used to add new content:
Method |
Description |
---|---|
append() |
Inserts content at the end of the selected element |
prepend() |
Inserts content at the beginning of the selected element |
after() |
Inserts content after the selected element |
before() |
Inserts content before the selected element |
The jQuery .append()
method inserts content at the end of the selected HTML element(s).
Try it yourself
The jQuery .prepend()
method inserts content at the beginning of the selected HTML element(s).
Try it yourself
You can easily add multiple new elements using both .append()
and .prepend()
in jQuery. Here's how you can add multiple elements at once using these methods.
In the following example, we create several new elements. The elements are created with text/HTML, jQuery, and JavaScript/DOM. Then we append the new elements to the text with the append()
method (this would have worked for prepend()
too) :
Try it yourself
The jQuery .after()
and .before()
methods are used to insert new content after or before the selected elements, respectively.
These methods are useful for inserting content in relation to existing elements without modifying their content directly.
Try it yourself
You can use .after()
and .before()
methods to add multiple new elements after or before the selected elements. Just like with .append()
and .prepend()
, these methods can handle multiple elements in a single call.
In the following example, we create several new elements. The elements are created with text/HTML, jQuery, and JavaScript/DOM. Then we insert the new elements to the text with the after()
method (this would have worked for before()
too) :
Try it yourself