jQuery insertAfter()

The jQuery after() and jQuery insertAfter() both methods are used to perform the same task of inserting additional contents after the selected elements.

Difference between jQuery after and insertAfter

The main difference between after() and insertAfter is in syntax and placement of the content and target.

In after() method, target is the selected element and content is placed as an argument of the method.

$(target).after(contentToBeInserted)  

In insertAfter() method, content is the selected element and target is placed as an argument of the method.

$(contentToBeInserted).insertAfter(target)  

Note: If you want to insert HTML elements before the selected element, you should use the insertBefore() method.

Syntax:

$(content).insertAfter(selector)  

Parameters of jQuery insertAfter() method

ParameterDescription
ContentIt is a mandatory parameter. It specifies the content which you want to insert.
SelectorIt is also a mandatory parameter. It specifies the place where you insert the content.>

jQuery insertAfter() method example

Let’s see an example of jQuery insertAfter() method.

<!DOCTYPE html>  

<html>  

<head>  

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  

<script>  

$(document).ready(function(){  

    $("button").click(function(){  

        $("<span><b>Hello javatpoint.com</b></span>").insertAfter("p");  

    });  

});  

</script>  

</head>  

<body>  

<button>Insert span element after each p element</button>  

<p>This is a tutorial website.</p>  

<p>This is a training institute.</p>  

</body>  

</html>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *