Home »
jQuery »
jQuery DOM Manipulation Methods
jQuery insertAfter() Method
jQuery | insertAfter() Method: Learn about the jQuery insertAfter() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 15, 2022
insertAfter() Method
Sometimes it is necessary to access a particular element on the web page. Not only that, at times there is a need to add, remove, or manipulated the text and the content using jQuery. When we need to add some content or text to an HTML document, there are various methods for it using jQuery. One of them is - the insertAfter() method. This method is a lot similar to the after() in jQuery since this method also helps you to add the content right after the selected element. The content that has to be added can be specified over here. The major difference between the after() and insertAfter() method is the different syntax of both. Here, unlike after(), the content has to be specified before following it comes to the selector.
insertAfter() Method Syntax
$('content').insertAfter('selector');
The element is selected using the selector. The content is the text or data that you wish to provide over there. When the content is specified within the insertAfter() method, then it can have any HTML tag, CSS properties, jQuery objects, or DOM elements in it.
Hence, this method is useful to add any type of content after the targeted location. It will add the specified content after all the matched elements with the selector. The below-provided example will help to understand the implementation of the insertAfter() method more easily. The content gets added as many times as the button is clicked.
jQuery insertAfter() Method Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<title>Document</title>
</head>
<body>
<h2>jQuery - InsertAfter</h2>
<p>Click the button to implement the insertAfter() method in jQuery.</p>
<button>insertAfter</button>
<hr>
<img style="height: 150px;" id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
</body>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("<h3>Thanks for visiting Include Help !!!</h3>").insertAfter('img');
});
});
</script>
</html>
Output: