jQuery Add
Using the jQuery, it is easy to add new content. Here are four jQuery methods to add new content:
append() prepend() after() before()
jQuery append() Method
The jQuery append() method is used to insert the content at the end of the selected HTML elements. Syntax:$(selector).append(content, function(index, html))
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});
$("#btn2").click(function(){
$("ol").append("<li>Appended item</li>");
});
});
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn1">Append text</button>
<button id="btn2">Append list items</button>
</body>
</html>
jQuery prepend() Method
jQuery prepend() method is used to insert the content at the beginning of the selected HTML contents. jQuery prepend() method is opposite of the jQuery append() method. Syntax:$(selector).prepend(content,function(index,html))
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("h2, p").prepend("<b>Prepended text</b>.");
});
$("#btn2").click(function(){
$("ol").prepend("<li>Prepended item</li>");
});
});
</script>
</head>
<body>
<h2> Hello World.</h2>
<p>this is a paragraph.</p>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn1">Prepend text</button>
<button id="btn2">Prepend list item</button>
</body>
</html>
jQuery after() method
The jQuery after() method is used to insert the content after the selected HTML elements. It is just like jQuery append() method. Syntax:$(selector).after(content,function(index))
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn2").click(function(){
$("h2").after("<i>After</i>");
});
});
</script>
</head>
<body>
<h2>Hello, world!</h2>
<button id="btn2">Insert after</button>
</body>
</html>
jQuery before() Method
The jQuery before() method is used to insert the content before the selected HTML elements. Syntax:$(selector).before(content, function(index)
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn2").click(function(){
$("h2").before("<i><b>Before</b> </i>");
});
});
</script>
</head>
<body>
<h2>Hello, World!</h2>
<button id="btn2">Insert before</button>
</body>
</html>