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:
- First, select the div element which needs to be copied into another div element.
- Select the target element where the div element is copied.
- Use the append() method to copy the element as its child.
Example: This example uses append() method to copy the div element into another div.
html
<!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;"> zambiatek </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:
- First, select the div element which need to be copy into another div element.
- Select the target element where div element is copied.
- Use the appendTo() method to copy the element as its child.
Example: This example uses appendTo() method to copy the div element into another div.
html
<!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;"> zambiatek </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:




