Skip to content

jQuery insertAfter() Method

  • by

The insertAfter() method in jQuery allows you to insert HTML content or a DOM element after the target element(s). This method takes in two parameters: the content or element to be inserted, and the target element or selector after which the content should be inserted.

Here’s the syntax for using insertAfter() method:

$(content).insertAfter(target)

The insertAfter() method is similar to the after() method in jQuery, but it inserts content after the target element(s) rather than after the selected element(s).

jQuery insertAfter() Method example

A simple example code uses the insertAfter() method to insert a new paragraph after an existing paragraph:

<!DOCTYPE html>
<html>
  <head>
    <title>Insert After Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <p>First paragraph</p>
    <p>Last paragraph</p>

    <script>
      var newParagraph = $("<p>New paragraph</p>");
      newParagraph.insertAfter($("p:first"));
    </script>
  </body>
</html>

Output:

jQuery insertAfter() Method

In this example, we create a new paragraph element with the text “New paragraph” using jQuery’s $() function, and then use the insertAfter() method to insert it after the first paragraph in the document. The selector $("p:first") selects the first <p> element in the document.

Comment if you have any doubts or suggestions on this Js insertAfter() Method topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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