Making Clone on Web Page using jQuery
Introduction
This
post shows how to make the clone of elements on web page using jQuery, for this
we will use .clone() method.
Sometimes
we want to copy (clone) elements on web page, for example, navigate menu can be
placed on header and footer too and there may be many situations come to us where
we need to clone. Why write something twice if we have opportunity to use
jQuery.
So, let's
create a demonstration page for this talk.
<body>
<h2>History of Visual Studio</h2>
<div class="mainBody">
Visual Studio's history probably begins
in <strong class="year">1975</strong> with Bill and
Paul's decision to create Altair BASIC.
Maybe you could start before that but I think that's as far back as you
could go and still say it's about Visual Studio at all – it's at that time that
Microsoft decided it was going to have software development products and not,
say, toaster automation.
</div>
<p>
Some informations.
</p>
<p>
Some more informations.
</p>
</body>
Let's
assume; we want to copy the 'mainBody' <div> and place it after first
<p>. To do this we will use following jQuery:
$('div.mainBody').clone().insertAfter('p:eq(0)');
Above
jQuery, making the clone of <div> that has class 'mainBody' and inserting
this new clone after first <p>, in DOM 0 refers the very first <p>,
1 refers the second <p> and so on.
Output
in Browser:
Take
one more assumption; what if we want to apply different style to cloned copy?
Now, to
do this we need to create a style class.
<style type="text/css">
.cloneStyle {
background: #ead3d3;
font: italic 1.4em "Times New Roman", Times, serif;
}
</style>
So, we
have a style now; let's add it to cloned copy.
$('div.mainBody').clone().insertAfter('p:eq(0)').addClass('cloneStyle');
Nothing
new here, just added one more attribute .addClass('cloneStyle') to existing
jQuery above.
Now,
look at the output in browser:
So,
that's all about the making clone on web page. You can dive deep in this topic
to achieve some more functionality.
Comments
Post a Comment