.clone()
In this chapter you will learn:
- Syntax and Description for .clone() method
- How to add a cloned element
- How to add a cloned tag
- 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>
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>
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>
Next chapter...
What you will learn in the next chapter: