A guide on cloning a div when clicked using jQuery

I'm looking to clone a div element after it when a button is clicked. I've come across solutions in vanilla JavaScript, but I really need a solution using jQuery as I struggle with it. Can anyone lend a hand?

This is my current setup:

<div class="example-1">
  <div class="example-2"> 
    <p>Example one</p>
    <p>Example two</p>

    <button class="btn-copy">Copy</button>
  </div>
</div>

This is what I aim for (after the click):

<div class="example-1">
  <div class="example-2"> 
    <p>Example one</p>
    <p>Example two</p>

    <button class="btn-copy">Copy</button>
  </div>

  <div class="example-2"> 
    <p>Example one</p>
    <p>Example two</p>

    <button class="btn-copy">Copy</button>
  </div>
</div>

Answer №1

To duplicate the div and add it, utilize the .clone() function to copy the div and .after() method to append it. If you want to copy only one div when using a class, you should use .closest(). Remember to include a boolean parameter in the clone method to ensure all data and event handlers are attached to the cloned element.

$(function(){
  $(".btn-copy").on('click', function(){
    var ele = $(this).closest('.example-2').clone(true);
    $(this).closest('.example-2').after(ele);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="example-1">
  <div class="example-2"> 
    <p>Example one</p>
    <p>Example two</p>

    <button class="btn-copy">Copy</button>
  </div>
</div>

Answer №2

recently updated

$(document).ready(function (){
  $('button').click(function (){
        $('.example-1').append($('.example-1').html())
    
        //console.log($('.example-1').html());
    })
  
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="example-1">
  <div class="example-2"> 
    <p>Example one</p>
    <p>Example two</p>
<button class="btn-copy">Copy</button>
  </div>
    
</div>

<!--this will only print once-->

Answer №3

give this a shot

$('.btn-copy').click(function ()
{
$('.example-1').append($('.example-2').html());

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="example-1">
  <div class="example-2"> 
    <p>Example one</p>
    <p>Example two</p>

    <button class="btn-copy" >Copy</button>
  </div>
</div>

Answer №4

If you want to duplicate an element, simply use the clone method. Here's an example:

$(document).on(click,'.btn-copy',function(){
  $(this).parents('.example-1').append($(this).parent().clone());
});

I hope this solution proves useful to you.

Answer №5

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<BODY>
<script>
$( document ).ready(function() {
  $(".btn-copy").click(function(event){
    console.log('You have clicked the button');
    var parentnode=this.parentNode;
    var OuterHtml=parentnode.outerHTML;
    var TopLevel=parentnode.parentNode;
    $(TopLevel).append(OuterHtml);
  });
});
</script>
<div class="example-1">
  <div class="example-2">
    <p>Example uno</p>
    <p>Example dos</p>
    <button class="btn-copy">Copy</button>
  </div>
</div>
</BODY>
</HTML>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Only one UI-Sref link is functional, while the remaining links are not

I have a situation where I have three links on an Angular template. The first link is working fine, but the other two are not. The first link displays the cursor as a pointer, while the second and third links display the cursor as auto/default. Here are th ...

Can Bootstrap be utilized by incorporating only specific parts of it?

Is there a way to easily separate specific parts of MyCSS.css and Bootstrap4.css? I'm having issues with Bootstrap breaking my CSS, but I still want to use certain components from Bootstrap4. While I know how to extract portions of Bootstrap4 CSS co ...

Container struggling to contain overflowing grid content items

While creating a grid in nextjs and CSS, I encountered an issue. Whenever I use the following code: display: grid; The items overflow beyond the container, even though I have set a maximum width. Instead of flowing over to the next row, the items just kee ...

Unable to display the Error 404 Component within a nested Component using React Router

When attempting to display the Error component if no matches are found, I encountered an issue - selecting a non-existing route only leads to a blank page. In the example, the Main component adds a sidebar menu and renders all its children inside it. If ...

Traversal of a binary tree in the order of visitation specified by the In

My task was to create a function that traverses a binary tree and returns an array of all its values in inorder. The code provided is: interface BinTree { root: number; left?: BinTree; right?: BinTree; }; const TreeInArray =(t:BinTree):number[] =>{ ...

Tips for adjusting column sizes in react-mui's DataGrid based on screen size

I would like the title column to occupy 3/4 of the full row width and the amount column to take up 1/4 of the full row width on all screens sizes (md, sx...). Here is the updated code snippet: import React from 'react' const MyComponent = () =&g ...

What is the most effective method for synchronizing data with HTML5 video playback?

I am currently developing a program that retrieves data from an android application and plays it back on a web browser. The android app allows users to record videos while logging data every 100ms, such as GPS location, speed, and accelerometer readings, i ...

The error alert must be displayed directly beneath the specific box

When error messages occur in this code, they are displayed through an alert box. However, I would prefer to have the error message appear below the specific text box instead. This means that when I click on the submit button and a field is left empty, the ...

Migrating a Node.js/Mongo application from Redhat Openshift2 to Openshift3: Where can I find the new MongoDB URI?

It seems like I have successfully set up node.js and mongoDB on my Openshift3 "Starter" Account. In the previous version, Openshift2, there was a full MONGODB URL environment variable provided. However, in the current version, there are only USER and PASS ...

Update the background image to be smoother, with no text overlay

I am working on a website where I need to smoothly change between background images. Here is the JavaScript code I currently have: var bg=[ 'images/best.jpg', 'images/61182.jpg', 'images/bg.jpg' ...

Unable to adjust the padding of the material UI Select component

I'm having trouble adjusting the padding of the Select component in order to align it with the size of my other text fields. Despite knowing that I need to make changes to nested components, I have yet to discover a viable solution. <div className ...

The width of the navigation bar adjusts after it becomes fixed to the top of the page

When scrolling past the navigation bar, it sticks to the top but expands beyond the container width. How can this issue be resolved so that the navigation bar retains its original width? Check out my code on GitHub: https://github.com/Archiie/MyPortfolio ...

Tips for creating animated clouds that move across the screen using Flash, jQuery, or JavaScript

Are there methods to create scrolling clouds using tools such as Flash, jQuery or JavaScript? If so, can you provide me with the code required to implement this on my homepage? I have three small cloud images that I would like to animate moving in the bac ...

Can anyone suggest a more efficient approach to handling variations using CSS?

Within the message component, there are currently only two variants available: error and success. This project is built using vue3 script setup and utilizes SCSS for styling. <script setup lang="ts"> defineOptions({ name: 'Notificat ...

What is the most efficient way to refresh a geometry's topology in ThreeJS?

Is there a way to efficiently update the vertices and faces of my geometry without creating new typed arrays and generating garbage for the JavaScript Garbage Collector? I currently use BufferedGeometry to create my geometry, but when updating vertex coord ...

"Implementing a Redux structure to enhance audio player functionality and effectively manage error

Imagine I am in the process of developing an audio player that includes a control panel for users to pause/play the currently selected track, along with the actual audio players. This involves actions such as pausing/playing the track, with the audio playe ...

Why are the height and width values I specified not matching the values returned?

I am currently learning HTML and JavaScript, specifically diving into the width() and height() methods in JavaScript. Setting the dimensions of div1 to 100px for height and 300px for width, I encountered a discrepancy when running the code. Upon execution ...

Can this layout be achieved using DIV elements?

Struggling to create a unique HTML/CSS layout that extends beyond the center? Imagine a standard horizontally centered page, but with one div expanding all the way to the right edge of the browser window. This design should seamlessly adjust to window res ...

Issue with opening mobile app from deep link in HTML email

My HTML form contains a deeplink that is submitted through the SendGrid API on nodeJS. After sending the email, users can view it but are unable to click on the deeplink. <!DOCTYPE html> <html> <head> ...

Learn how to dynamically display an image if the original one fails to load by utilizing the image component available in Next.js

I am currently fetching data for an image. The source of the image is stored in the variable "movie.primaryImage.url". However, there are instances when the image fails to load. I have attempted to implement conditional rendering so that a fallback image ...