Skip to content
jQuery prepend with examples
In This Tutorial
The prepend method
The prepend method, as opposed to jQuery append method, adds content at the beginning of specified element. For example:
p.prepend (“content”) will add content at the beginning of paragraphs in the document.
See an example of prepend method
This chapter only explains how to use the $.prepend method with examples. First of all syntax of using prepend() method in jQuery.
Syntax of prepend() method
The syntax of prepend jQuery method is:
selector.prepend(“content to be added”);
Where selector can be an element where you want to add content.
Example of using .prepend in paragraph
In the following example, we will show you how to add simple text at the beginning of a paragraph. As you click on the button in the example page, it will add given plain text at the beginning of the paragraph.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
<html>
<head>
<script src=“http://code.jquery.com/jquery-1.10.1.min.js”></script>
<script>
$(document).ready(function(){
$(“#addcontent”).click(function(){
$(“#content”).prepend(” Add content! “);
});
});
</script>
</head>
<body>
<button id=“addcontent”>Add content</button>
<p id=“content”>Paragraph where content will insert! </p>
</body>
</html>
|
Similarly, you can add content that contains HTML tags by using prepend method. For example, it can contain <i> tag, links, images, etc.
The example below adds bold text and a link as you click on the button.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
<html>
<head>
<script src=“http://code.jquery.com/jquery-1.10.1.min.js”></script>
<script>
$(document).ready(function(){
$(“#addcontent”).click(function(){
$(“#content”).prepend(“<b>text in bold</b> <a href=’http://www.example.com’>a link</a> “);
});
});
</script>
</head>
<body>
<button id=“addcontent”>Add content</button>
<p id=“content”>Paragraph where content will insert! </p>
</body>
</html>
|
Related: append method of jQuery | jQuery after | jQuery before
Leave A Comment?