.appendTo()

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>//  ww w  .  j a  va  2s.  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>/*ww  w  .  ja va 2s .  c  o  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 .  j  a  v  a2  s  . co  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  . ja v a2 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

The code above generates the following result.

.appendTo()

Reverse of $(A).append(B)


<!--  w w w  .  j  av  a 2  s  .  c  om-->
<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

The code above generates the following result.

.appendTo()
Home »
  Javascript Tutorial »
    jQuery Reference »
      DOM
...
$("html tags")
.add()
.addClass()
.after()
.andSelf()
.append()
.appendTo()
.attr()
.before()
.children()
.clone()
.closest()
.contents()
.css()
.detach()
.filter()
.first()
.get()
.has()
.hasClass()
.height()
.html()
.index()
.innerHeight()
.innerWidth()
.insertAfter()
.insertBefore()
.is()
.last()
.map()
.next()
.nextAll()
.nextUntil()
.not()
.offset()
.offsetParent()
.outerHeight()
.outerWidth()
...