.after()

In this chapter you will learn:

  1. Syntax and Description for .after() method
  2. How to insert text node after paragraph
  3. How to insert hard coded HTML element
  4. How to insert a selected node from the same HTML document

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>
 <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">//from j  a v  a2 s .  c om
 <h2>Header</h2>
 <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>
<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><!--from  j ava  2s  .  c  o m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
              $("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><!--   j  a  v  a 2 s  .c om-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
               $("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><!--from j a v a  2s .com-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("p").after( $("b") );
        });
    </script>
  </head>
  <body>
    <body>
         <b>b</b>
         <p>p</p>
  </body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. Syntax and Description for .andSelf() DOM method
  2. How to reference current and next element
  3. How to add tag back and move on