ArdMir ArdMir - 1 month ago 5
Javascript Question

Why appendChild is not working with node type?

This might be a little too simple for me to diagnose, but I'm wondering why am I not able to add 'img' to the 'div'.

console does pass the images but it's not appending. I want to remove the elements after.

Thanks in advance

var theLeft = document.createElement('div');
var theLeftElements = theLeftSide.getElementsByTagName('img');
theLeftSide.appendChild(theLeft);
theLeft.appendChild(theLeftElements);

Dai Dai
Answer

getElementsByTagName returns a NodeList (Similar to an array), whereas appendChild expects its argument to be a Node.

You will need to iterate over the list yourself:

var imgs = document.getElementsByTagName('img');
for( var i = 0; i < imgs.length; i++ ) {
    parent.appendChild( imgs[i] );
}