I was wondering how I can duplicate a DIV
element a few times through JavaScript without duplicating the DIV in my html code?
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
-
11
-
1
-
@utopy You can repeat the action as many times as you'd like (just be sure to change the
.id
property of divClone so it won't lead to multiple IDs. If you're looking for a language construct in JavaScript that lets you repeat actions multiple times without actually writing them multiple times - check outfor
andwhile
loops. Check out the basic examples section in this page. – Benjamin Gruenbaum Oct 20 '13 at 20:01 -
I don't see what's so bad about suggesting jQuery. If the user is new to javascript it's worth making them aware of this excellent framework. They may never have heard of it before. – geedubb Oct 20 '13 at 20:32
-
7@geedubb Several things. First, Please consider reading about what a framework is (hint: jQuery is not a framework). Second, many reasons otherwise we'll end up here. Lack of understanding of how the DOM API works, or what it is makes for some pretty bad programmers. You use libraries on top of foundations - first learn the language and APIs and then learn abstractions. You don't want to encourage bad practices and poor code. You want to encourage actual understanding. – Benjamin Gruenbaum Oct 20 '13 at 20:37
.clone()
. On usage, I'll leave it to you to read it up yourself. – Terry Oct 20 '13 at 19:53