为什么appendChild不能处理节点类型

Why appendChild is not working with node type?

本文关键字:节点 类型 处理 不能 appendChild 为什么      更新时间:2023-09-26

这对我来说可能有点太简单了,但我想知道为什么我不能将'img'添加到'div'。

控制台确实传递图像,但它不是附加的。我想删除后面的元素

Thanks in advance

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

getElementsByTagName返回NodeList(类似于数组),而appendChild期望其参数为Node

你需要自己遍历列表:

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