Open In App

How to copy the content of a div into another div using jQuery ?

Given an HTML document containing some div element and the task is to copy a div content into another div as its child using jQuery. There are two approaches to solve this problem that are discussed below: 

Approach 1:



Example: This example uses append() method to copy the div element into another div. 




<!DOCTYPE HTML>
<html>
 
<head>
    <title>
        How to copy the content of a div
        into another div using jQuery ?
    </title>
 
    <script src=
    </script>
 
    <style>
        .parent {
            background: green;
            color: white;
            width: 400px;
            margin: auto;
        }
 
        .child {
            background: blue;
            color: white;
            margin: 10px;
        }
    </style>
</head>
 
<body id="body" style="text-align:center;">
 
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <h3>
        Click on the button to copy
        a DIV into another DIV
    </h3>
 
    <div class="parent">
        Outer DIV
        <div class="child">
            Inner DIV
        </div>
    </div>
    <br>
 
    <div class="parent" id="parent2">
        Outer DIV
    </div>
    <br>
 
    <button onclick="GFG_Fun()">
        Click Here
    </button>
 
    <script>
        function GFG_Fun() {
            let $el = $('.child').clone();
            $('#parent2').append($el);
        }
    </script>
</body>
 
</html>

Output:



Approach 2:

Example: This example uses appendTo() method to copy the div element into another div. 




<!DOCTYPE HTML>
<html>
 
<head>
    <title>
        How to copy the content of a div
        into another div using jQuery ?
    </title>
 
    <script src=
    </script>
 
    <style>
        .parent {
            background: green;
            color: white;
            width: 400px;
            margin: auto;
        }
 
        .child {
            background: blue;
            color: white;
            margin: 10px;
        }
    </style>
</head>
 
<body id="body" style="text-align:center;">
 
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <h3>
        Click on the button to copy
        a DIV into another DIV
    </h3>
 
    <div class="parent">
        Outer DIV
        <div class="child">
            Inner DIV
        </div>
    </div>
    <br>
 
    <div class="parent" id="parent2">
        Outer DIV
    </div>
    <br>
 
    <button onclick="GFG_Fun()">
        Click Here
    </button>
 
    <script>
        function GFG_Fun() {
            $('.child').clone().appendTo('#parent2');
        }
    </script>
</body>
 
</html>

Output:


Article Tags :