1

I have a very simple html code here. I want to store the whole div test_area and then create it when I need it. For now, let's assume that I want to duplicate it and put the clone below the existing element, how can I do that? Here's what I tried to do which didn't work (specifically the innerHtml line):

<body>
    <div class="test_area" id="test_area">
        <h1>
            This is a test
        </h1>
    </div>
</body>

<script>
    let current_element = document.getElementById('test_area')
    let clone = document.createElement('div')
    clone.innerHTML = current_element
    document.body.appendChild(clone)
</script>

In the end I want the final html version to look like this:

This is a test

This is a test

LDinos
  • 103
  • 1
  • 7

4 Answers4

1

Depends what you want to do with the element. You can store it in a variable and then render somewhere or you could store it to localstore or send to server or what ever you like. Here is a simple example:

<div class="test_area" id="test_area">
    <h1>
        This is a test
    </h1>
</div>

<div id="clonearea"></div>

 const current_element = document.getElementById('test_area');
 const clonearea = document.getElementById('clonearea');
 const clone = current_element.cloneNode(true);
 clonearea.appendChild(clone);

You can read more about cloning here: https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode

And here is a codepen example: https://codepen.io/shnigi/pen/LYRQGOW

Shnigi
  • 972
  • 9
  • 19
0

You can simply convert the old object in a JSON, and then parsing it and save it to a var.

let myObject = JSON.parse( JSON.stringify( myOldObject ) );

this way you can access myObject and display it whenever you want.


Take a look to this question :
What is the most efficient way to deep clone an object in JavaScript?

Emanuele
  • 192
  • 4
0

This is not cloning, but a way to create and append in one line:

document.getElementById("test_area").appendChild(Object.assign(document.createElement("h1"), {textContent: "This is a test"}))
<body>
    <div class="test_area" id="test_area">
        <h1>
            This is a test
        </h1>
    </div>
</body>

To actually clone, use cloneNode

https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode

let p = document.getElementById("test_area").children[0]
let p_prime = p.cloneNode(true)

document.getElementById("test_area").appendChild(p_prime)
<body>
    <div class="test_area" id="test_area">
        <h1>
            This is a test
        </h1>
    </div>
</body>
NVRM
  • 11,480
  • 1
  • 88
  • 87
0

Apparently the only thing i should have done to fix this problem is use the variable's innerHTML and append it on the body, like this. I had totally forgotten that current element is an object, not the html code itself.

const current_element = document.getElementById('test_area');
document.body.appendChild(current_element.innerHTML)
LDinos
  • 103
  • 1
  • 7