The jQuery append() method inserts the specified content at the end of the selected elements.
Syntax of jQuery append() method
$(selector).append(content,function(n))
content: This specifies the content which you want to append at the end of the selected elements, it can be HTML elements, jQuery objects, DOM elements. You must specify this parameter as it is a mandatory parameter.
function (n): It is an optional parameter. You can pass this function instead of content as a parameter to the append() method. This function returns the content that is inserted at the end of the selected elements.
The parameter n to the function, represents the index of the selected elements. For example, if the selected elements are paragraphs then the n=0 represents the index of the first paragraph, n=1 represents the index of the second paragraph and so on.
Example 1: jQuery append() method
In this example, we are appending content at the end of the paragraph as well as end the end of the list. $(p)
selected all the paragraph and $(p).append(Hi, BeginnersBook.com followers!)
appended the message at the end of each paragraph.
Similarly $(ol)
selected the ordered list and $(ol).append(New List Item)
appended this new item at the end of the list.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#b1").click(function(){
$("p").append(" <b><i>Hi, BeginnersBook.com followers!<i></b>.");
});
$("#b2").click(function(){
$("ol").append("<li><b>New List Item</b></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="b1">Append text</button>
<button id="b2">Append item</button>
</body>
</html>
Output:
Before button click:
After “Append text” button click:
After “Append item” button click:
Example 2: Append content using a function
We can also append the content using a function. As shown in the following example, we have passed a function to the append() method and the content generated by this function is appended at the end of selected elements.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").append(function(n){
return "<b><i>This paragraph has index " + n + ".</i></b>";
});
});
});
</script>
</head>
<body>
<p>This example is on beginnersbook.com.</p>
<p>This is another paragraph.</p>
<button>Append all paragraph indexes.</button>
</body>
</html>
Output:
Before button click:
After button click:
Leave a Reply