How to duplicate a div in JavaScript

后端 未结 1 1152
[愿得一人]
[愿得一人] 2020-12-03 09:01

I was wondering how I can duplicate a DIV element a few times through JavaScript without duplicating the DIV in my html code?

相关标签:
1条回答
  • 2020-12-03 09:58

    Let's assume the you selected the div doing something like:

    var myDiv = document.getElementById("myDivId");
    

    The DOM API contains a cloneNode method which you can use

    var divClone = myDiv.cloneNode(true); // the true is for deep cloning
    

    Now you can add it to the document

    document.body.appendChild(divClone);
    

    Here is a short self contained code example illustrating this

    0 讨论(0)
提交回复
热议问题