EN
JavaScript - clone indicated element
0 points
In this article, we would like to show you how to clone an indicated HTML element using JavaScript.
Quick solution:
xxxxxxxxxx
1
element.cloneNode(boolean);
Where the boolean
value specifies whether to clone the whole subtree (all child nodes) of the element
. By default, it's set to false
.
Warning:
Cloning an item may lead to duplicate element IDs in a document and these should remain unique!
In this example, we use cloneNode()
method with true
value passed as an argument to copy an element with the whole subtree, which in this case is only a text node.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="my-element">My element text...</div>
5
<script>
6
7
myElement = document.querySelector('#my-element');
8
9
// clone myElement with all its children (text node)
10
clone = myElement.cloneNode(true);
11
12
// append cloned element in the body
13
document.body.appendChild(clone);
14
15
</script>
16
</body>
17
</html>
In this example, we use cloneNode()
method with false
value passed as an argument to copy an element without its childNodes (the text node).
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div id="my-element">My element text...</div>
5
<script>
6
7
myElement = document.querySelector('#my-element');
8
9
// clone myElement without its children
10
clone = myElement.cloneNode(false);
11
12
// display cloned element outerHTML in the console
13
console.log(clone.outerHTML);
14
15
</script>
16
</body>
17
</html>