jQuery .appendTo() method appends content to target element

Syntax and Description

.appendTo(target)

inserts every element in the set of matched elements at the end of the target. target: is a selector, element, HTML string, or jQuery object. The matched elements will be inserted at the end of the element(s) specified by this parameter.

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

Consider the following HTML code:


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

When applying the following code.

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

The result would be:


<h2>Header</h2>/*from   w  w  w.j a va2s  . co  m*/
<div class="container">
 <div class="inner">
 Hello
 <p>Test</p>
 </div>
 <div class="inner">
 InnerText
 <p>Test</p>
 </div>
</div>

The following code sselects an element on the page and inserts it into another.

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

If an element selected is inserted some where else, it will be moved into the target not cloned.


<div class="container">
 <div class="inner">Hello</div>
 <div class="inner">InnerText</div>
 <h2>Header</h2>//www . java  2 s .  c o m
</div>

Add hard code tag to another tag

The following code adds tag to body element.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <style type="text/css">
        .changeP { font-weight: bold; color:red;}
    </style>
    <script type="text/javascript">
       $(document).ready(function(){<!-- w w w. j  ava2  s  .c  om-->
         $("<div><p>Hello</p></div>").appendTo("body")
       });
    </script>
  </head>
  <body>
   <form>
      <input type="radio" value="Option">
   </form>
  </body>
</html>

Click to view the demo

Reverse of $(A).append(B)


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

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities