Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
347 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...