jQuery .clone() method makes copies of another elements

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>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from  w  ww  . j a va2  s . c  om-->
              $("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>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!-- w w w  .java  2 s  .  co m-->
           $("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>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--   w  w w. java 2s.c om-->
           $("p").clone().appendTo(document.body);
        });
    </script>
  </head>
  <body>
    <body>
          <p>java 2s.com</p>
  </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities