How to append an element after an element using jQuery?

To append an element after an element using jQuery, use the insertAfter() method. This method moves or inserts the selected element after the target element in the DOM.

Syntax

The basic syntax of the insertAfter() method is ?

$(content).insertAfter(target)

Where content is the element to be inserted and target is the element after which the content will be placed.

Example

You can try to run the following code to learn how to append an element after an element using jQuery ?

<html>
  <head>
    <title>The jQuery Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    
    <script>
      $(document).ready(function() {
        $("div").click(function () {
          $("#source").insertAfter(this);
        });
      });
    </script>
    
    <style>
      .div {
        margin: 10px;
        padding: 12px;
        border: 2px solid #666;
        width: 60px;
        cursor: pointer;
      }
    </style>
  </head>
  
  <body>
    <p>Click on any square below to see the result:</p>
    
    <div class="div" id="source">Source</div>
    <div class="div" style="background-color:blue;">Blue</div>
    <div class="div" style="background-color:green;">Green</div>
    <div class="div" style="background-color:red;">Red</div>
  </body>
</html>

In this example, when you click on any colored square, the source element will move and position itself right after the clicked element.

Conclusion

The insertAfter() method is a powerful jQuery function that allows you to dynamically reposition elements in the DOM by placing them after specific target elements.

Updated on: 2026-03-13T19:24:18+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements