The jQuery insertAfter() method inserts the specified html elements after the selected elements. If the specified html element already exists, then the existing element will be moved from the current position and inserted after the selected elements.
Syntax of jQuery insertAfter() method
$(content).insertAfter(selector)
content: This is a mandatory parameter. This contains HTML elements that are inserted after the selected elements by insertAfter()
method. This content parameter must always contain html tags.
Important Note: If content field contains already existing html elements then those elements will be moved from the current position and inserted after the selected elements.
selector: This is also a mandatory parameter. This selects the elements, after which the specified content is inserted.
jQuery insertAfter() method Example
In the following example, we are using insertAfter() method to move the H1 tag after the p elements. The H1 tag already exists so the existing H1 tag is moved from current place and appended after the p elements as shown in the output screenshots.
<!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(){
$("h1").insertAfter("p");
});
});
</script>
</head>
<body>
<h1>This is the H1 heading of the page.</h1>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<button>Move and insert H1 heading after each paragraph.</button>
</body>
</html>
Output:
Before the button click:
After the button click: The H1 tag is moved and appended after each paragraph.
Leave a Reply