Search code examples
javascriptchild-nodes

JS- appendChild from one div object to another


I'm not quite sure why this code does not do what I intend it to. I have two div objects, with a series of input tags within each of them, like so:

<div id="div1">
    <input type....></input>
    etc,etc,etc
</div>

I would like to take an input tag from one, and append to the other, and then change the style of all the inputs within that div. This is what I mean :

var div1 = document.getElementById("div1").childNodes;
var div2 = document.getElementById("div2").childNodes;
div1.appendChild(div2[1]);
var i;
for (i = 0; i < div1.length; i++) {
    div1[i].style.backgroundColor = "red";
}

I understand that whitespace is read between the tags when childNodes is used, however, I made sure that div2[1] is not whitespace. I also understand that there are other ways of doing what I am trying to do, and in fact I found other ways of doing it successfully, but I want to know why the above code, using childNodes, does not work; i.e. why none of the backgroundColors change to red.


Solution

  • So the problem is here

    div1 is not an element, is a list of nodes. And setting style of a node without checking if it is an element will give you error.

    To make it works you should do:

    var div1 = document.getElementById("div1");
    var div1nodes = document.getElementById("div1").childNodes;
    var div2nodes = document.getElementById("div2").childNodes;
    div1.appendChild(div2nodes[1]);
    var i, el;
    for (i = 0; i < div1nodes.length; i++) {
        el = div1nodes[i];
        if (el.nodeType === 1) {
          el.style.backgroundColor = "red";
        }
    }