Making Clone on Web Page Using jQuery

Introduction

This post shows how to clone elements of a web page using jQuery; for this we will use the .clone() method.

Sometimes we want to copy (clone) elements of a web page; for example, a navigate menu can be placed on the header and on the footer too and there may be many situations that occur where we need to make a clone. Why write something twice if we have the opportunity to use jQuery.

So, let's create a demonstration page for this article.

<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 the first <p>. To do this we will use the following jQuery:

$('div.mainBody').clone().insertAfter('p:eq(0)');

In the above jQuery, making the clone of the <div> that has the class "mainBody" and inserting this new clone after the first <p>, in DOM 0 refers the very first <p>, 1 refers the second <p> and so on.

Output in the browser:

image001.png

Take one more assumption; what if we want to apply a different style to the cloned copy??

Now, to do that 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 the cloned copy.

$('div.mainBody').clone().insertAfter('p:eq(0)').addClass('cloneStyle');

Nothing new here; we just added one more attribute .addClass('cloneStyle') to the existing jQuery above.

Now look at the output in the browser:

image002.png

So, that's all about making a clone in a web page. You can dive deeper into this topic to achieve more functionality.