Description:
The jQuery insertAfter() methods is used to add the contents after the selected elements.
Syntax
- $(selector).insertAfter(target)
Difference between jQuery after() and insertAfter()
The main difference between after() and insertAfter() method is their syntax and their placement of the target and content location.
- after(): $(selector).after(content)
- insertAFter : $(content).insertAfter(selector)
Example:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<style>
.container {
border: 5px solid #1a80b6;
padding: 10px;
display: inline-block;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('#btnClick').click(function () {
$('<div style="color:#ff0000"> This is Newly added text </div>').insertAfter("#divcontainer");
})
});
</script>
</head>
<body>
<button id="btnClick">Click to Add content using insertAfter()</button><br /><br />
<div id="divcontainer" class="container">
<div>
This is Default text
</div>
</div>
</body>
</html>Output:
By clicking the button, “this is Newly added text” will append after the selected div (divcontainer).