jQuery .after() method inserts elements after selected one

Syntax and Description

  • .after(content)
    content: An element, HTML string, or jQuery object to insert after each matched element
  • .after(function)
    function: A function that returns an HTML string to insert after each matched element

.after() method inserts content specified by the parameter after each element in the set of matched elements.

Consider the following HTML code:


<div class="container">
 <h2>Header</h2>/*  w  w  w.ja va  2  s .  co  m*/
 <div class="inner">Hello</div>
 <div class="inner">InnerText</div>
</div>

The following code creates content and insert it after several elements at once.

$('.inner').after('<p>Test</p>');

The Results would be:


<div class="container">
 <h2>Header</h2>// ww  w.ja va 2 s  . c  om
 <div class="inner">Hello</div>
 <p>Test</p>
 <div class="inner">InnerText</div>
 <p>Test</p>
</div>

The following code selects an element on the page and inserts it after another.

$('.container').after($('h2'));

The results would be:


<div class="container">
 <div class="inner">Hello</div>
 <div class="inner">InnerText</div>
</div>//w w  w. j av  a  2s  .  c  o m
<h2>Header</h2>

Its return value is the jQuery object, for chaining purposes.

Insert text node

The following code adds text node created from document.createTextNode after selected paragraph.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!-- ww  w .j a v a2  s.c o m-->
              $("p").after( document.createTextNode("Hello") );

        });
    </script>
  </head>
  <body>
    <body>
         <p> a</p><b>b</b>
  </body>
</html>

Click to view the demo

Insert hard coded HTML element

The following code inserts hard coded HTML element after a paragraph..


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!-- ww w  . j a v  a  2 s  .c  o  m-->
               $("p").after("<b>Hello</b>");
        });
    </script>
  </head>
  <body>
    <body>
         <p> a</p><b>b</b>
  </body>
</html>

Click to view the demo

Insert a selected node

The following code switches the sequence of two tags.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--   ww  w .  ja v  a  2 s.  c o m-->
            $("p").after( $("b") );
        });
    </script>
  </head>
  <body>
    <body>
         <b>b</b>
         <p>p</p>
  </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities