jquery
  1. jquery-insertafter

jQuery insertAfter()

jQuery insertAfter() is a jQuery method that allows you to insert HTML content or an existing HTML element after another HTML element.

Syntax

The syntax for insertAfter() is as follows:

$(content).insertAfter(target)

Here, content is the HTML element or content that you want to insert after the target element.

Use

The insertAfter() method is useful for dynamically adding content to your web page. It allows you to specify the location where the content should be inserted and can be used to move elements as well.

Example

Here, we have a basic HTML page where we want to move a <p> tag after a <div> tag using insertAfter():

<!DOCTYPE html>
<html>
<head>
  <title>jQuery insertAfter() Example</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div>
    <h1>Welcome to my website!</h1>
  </div>
  <p>This paragraph should be moved to after the div tag.</p>
  <script>
    $( "p" ).insertAfter( "div" );
  </script>
</body>
</html>
Try Playground

In this example, we use insertAfter() to move the <p> tag after the <div> tag. The result is that the content of the page is rearranged so that the <div> tag comes before the <p> tag.

Summary

jQuery insertAfter() is a useful method that allows you to insert HTML content or elements after another element. It is useful for dynamically adding content to your web page and can be used to rearrange elements as well. Give it a try in your own jQuery projects to see how it can help you customize your web pages and improve their functionality.

Published on: