The jQuery after() method inserts the specified content after the selected elements.
Syntax of jQuery after() method
$(selector).after(content, function(n))
Here, content represents the content that is inserted after the selected elements. This content can be HTML elements, jQuery objects or DOM elements or a simple text/value.
$(selector): This selects the elements after which the content is inserted by after() method. Read more: jQuery selectors.
function(n): This is an optional parameter, it can be used when you need to insert content using the function. Here, n represents the index for the selected elements. Refer the second example to understand the use of function in after() method.
Example 1: jQuery after() – Adding text after the paragraphs
In this example, we are adding a text after each paragraph using after() method. On the click event, the method after() adds the specified text after the selected element (paragraphs in this example). If you keep clicking the button, the method would keep on adding the specified text on top of the previously added content by after() method.
<!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").after("<p>Hi BeginnersBook.com readers!</p>");
});
});
</script>
</head>
<body>
<button>Insert specified message after each paragraph</button>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
</body>
</html>
Output:
Before the button click:
After the button click:
Example 2: jQuery after() – Insert content using a function
We can insert the content after the selected element using a function as well. In this example, we are passing the function as a parameter to the after() method. This function returns the content that is added by the method, the content can be different for the selected elements based on index (represented by the n).
As you can see the content added is different for each paragraph as the index value is different for each paragraph. The first paragraph has index value as 0 and the second paragraph has index value 1 and so on.
<!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").after(function(n){
return "<div>Index of above paragraph is: " + n + ".</div>";
});
});
});
</script>
</head>
<body>
<h1>BeginnersBook.com Example: jQuery after() method</h1>
<button>Insert content after each paragraph</button>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
</body>
</html>
Output:
Before the button click:
After the button click:
Leave a Reply