.clone()

In this chapter you will learn:

  1. Syntax and Description for .clone() method
  2. How to add a cloned element
  3. How to add a cloned tag
  4. How to append clone to document body

Syntax and Description

.clone([withEvents])

makes copies of elements.

withEvents (optional) is a boolean indicating whether event handlers should be copied along with the elements. Return value is a new jQuery object referencing the created elements.

Adds a cloned element to a paragraph

The following code clones the b element and then insert it to the paragraph.

<html><!-- j ava  2  s  .  c  o m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
              $("b").clone().prependTo("p");
        });
    </script>
  </head>
  <body>
    <body>
       <b>Hello</b><p>, how are you?</p>
    </body>
</html>

Click to view the demo

Append a cloned tag

The following code adds cloned tag. It first creates a clone of a paragraph tag. Then it adds a hard coded span element to the cloned paragraph tag. Finally it appends them to the body element.

<html><!--from   j a  va 2  s. co m-->
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
           $("p").clone().add("<span>Again</span>").appendTo(document.body);
        });
    </script>
    <style>
      div { width:40px; height:40px; margin:10px; float:left;}
    </style>
  </head>
  <body>
    <body>
          <p>Hello ja v a2s.com</p>
  </body>
</html>

Click to view the demo

Append clone to document body

The following code clones a paragraph and then adds it to the document body.

<html><!--   j av a2  s  .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").clone().appendTo(document.body);
        });
    </script>
  </head>
  <body>
    <body>
          <p>java 2s.com</p>
  </body>
</html>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. Syntax and Description for .closest()
  2. How to get the first span element for a click event