Kristoffer Kristoffer - 1 year ago 62
HTML Question

Old input-text-values in div when using innerHTML

I have a Javascript/innerHTML-problem. To make it easier to understand I have written this code:

<div id="testdiv_from">
<input type="text" id="text1" value="13"/>

<div id="testdiv_to">

<input type="button" onclick="save();"/>

function save() {
document.getElementById("testdiv_to").innerHTML = document.getElementById("testdiv_from").innerHTML;

I want to copy the content in testdiv_from to testdiv_to. But: If I change the value on the input text-element from 13 to 14, the new value doesn't want to "accompany".

Do you have any ideas how to transfer the new input-text-values and not the old ones inside the div layer? Is it wrong to use innerHTML?

Answer Source

If you look at input element in Developer tools, you will see that input element is a wrapper of hidden div element, so when you change value of input element, its changes value of hidden div element, and not an attribute.

If you want to copy content of one element into another element, would be better if you use standard DOM property/methods, such as Node.cloneNode.


function save() {
    var divTo = document.getElementById("testdiv_to"),
        divFrom = document.getElementById("testdiv_from");
    // since, you said that you have multiple input elements that you want to copy,
    // you should loop through each node and clone it.
    [], function (node) {
        // the difference between innerHTML and node.cloneNode(true) is that
        // cloneNode with "deep copy", copies that hidden element too.

FYI: If you want to copy an element, you shouldn't add id attribute to those elements, since id ought to be unique per document. Instead, add class or change id while cloning.