.appendTo()

In this chapter you will learn:

  1. Syntax and Description for .appendTo() method
  2. How to add hard code tag to another tag
  3. $(A).append(B) is reverse of $(A).appendTo(B)

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>
<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  ja  va  2s.  com*/
<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>
</div>

Add hard code tag to another tag

The following code adds tag to body element.

<html><!--from  j  ava 2s. c  o m-->
  <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(){
         $("<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)

<html><!--from j  av 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").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

Next chapter...

What you will learn in the next chapter:

  1. Description for .attr()
  2. Syntax for .attr() getter
  3. Syntax for .attr() setter
  4. How to set image src from its title
  5. attr and loop
  6. .attr getter demo
  7. .attr setter demo
  8. access a property on the first matched element
  9. Add attribute and clear attribute
  10. Set Image URL title alt
  11. attr value calculation
  12. .attr with function return value