jQuery - Add Elements
With jQuery, it is easy to add new elements/content.
Adding new HTML content
We will learn four jQuery methods for adding 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).
Example
$
(
"
p
"
)
.
append
(
"
Append text
"
)
;
Try it »
jQuery prepend() method
The jQuery prepend() method inserts content at the beginning of the selected elements.
Example
$
(
"
p
"
)
.
prepend
(
"
Prepend text
"
)
;
Try it »
Adding several new elements with append() and prepend()
In the examples above, we inserted only text/HTML at the beginning/end of the selected elements.
However, the append() and prepend() methods can take an unlimited number of new elements as parameters. You can generate text/HTML with jQuery (as in the example above), or via JavaScript code and DOM elements.
In the example below, we create several new elements. These can be created with text/HTML, jQuery or JavaScript/DOM. We then append these new elements to the text with the append() method (the same works for prepend()):
Example
function
appendText
(
)
{
var
txt1
=
"
Text-1.
"
;
//
Create text using an HTML tag
var
txt2
=$
(
"
"
)
.
text
(
"
Text-2.
"
)
;
//
Create text using jQuery
var
txt3
=
document
.
createElement
(
"
p
"
)
;
txt3
.
innerHTML
=
"
Text-3.
"
;
//
Create text using DOM text with DOM
$
(
"
body
"
)
.
append
(
txt1
,
txt2
,
txt3
)
;
//
Append new elements
}
Try it »
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.
Example
$
(
"
img
"
)
.
after
(
"
Add text after
"
)
; $
(
"
img
"
)
.
before
(
"
Add text before
"
)
;
Try it »
Adding several new elements with after() and before()
The after() and before() methods can take an unlimited number of new elements as parameters. New elements can be created with text/HTML, jQuery or JavaScript/DOM.
In the example below, we create several new elements. These can be created with text/HTML, jQuery or JavaScript/DOM. We then insert these new elements into the text with the after() method (the same works for before()):
Example
function
afterText
(
)
{
var
txt1
=
"
I
"
;
//
Create elements using HTML
var
txt2
=$
(
"
"
)
.
text
(
"
love
"
)
;
//
Create elements using jQuery
var
txt3
=
document
.
createElement
(
"
big
"
)
;
//
Create elements using DOM
txt3
.
innerHTML
=
"
jQuery!
"
; $
(
"
img
"
)
.
after
(
txt1
,
txt2
,
txt3
)
;
//
Add text after an image
}
Try it »