Search code examples
javascriptjqueryhtmlclone

Clone <div> with all elements


I have this div (representing a location room):

<div class="card transition">
    <h2 class="transition1"></h2>
    <p class="hovering"></p>
    <div class="cta-container transition"><a href="#" class="cta">Open room</a></div>
    <div class="card_circle transition"></div>
</div>

Also I'm doing an AJAX request in order to get the number of location rooms. For example if I have 9 location rooms, I want to dinamically generate 9 div, for each room, containing the same elements as the div above.

I've tried this so far (using an "add" button) to see if I can clone the div, but without success:

$(function () {
    $("#add").click(function () {
        div = document.createElement('div');
        $(div).addClass("cta-container transition").html($('.cta-container transition').clone());
        $(".card transition").append(div);
    });
});

Solution

  • Here's how to clone a div and its whole children in native:

    var myDiv=document.getElmentById("myDiv").cloneNode(true);
    

    Then you can do:

    yourElement.appendChild(myDiv);