Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/417.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript中将元素添加到HTMLCollection中?_Javascript_Html - Fatal编程技术网

如何在javascript中将元素添加到HTMLCollection中?

如何在javascript中将元素添加到HTMLCollection中?,javascript,html,Javascript,Html,我有一个HTMLCollection对象,我可以使用它来操作HTMLCollection的内容。我想知道向HTMLCollection的第一个、最后一个或任何特定索引添加div元素的方法。请提出一些建议。 这里的NDIV是HTML集合 var Div = document.createElement('div'); for(i=0; i<9; i++){ Div.appendChild(nDivs[0].children[0]); } Div

我有一个HTMLCollection对象,我可以使用它来操作HTMLCollection的内容。我想知道向HTMLCollection的第一个、最后一个或任何特定索引添加div元素的方法。请提出一些建议。 这里的NDIV是HTML集合

    var Div = document.createElement('div');
    for(i=0; i<9; i++){
        Div.appendChild(nDivs[0].children[0]);
    }
    Div.id = nDivs[0].id;
    nDivs[0].parentNode.removeChild(nDivs[0]);

    nDivs.appendChild(Div); //this is creating problem..need an alternative to this
    document.getElementById("ABC").appendChild(nDivs[nDivs.length - 1]);
var Div=document.createElement('Div');
对于(i=0;i根据

HTMLCollection
是一个接口,表示 元素(按文档顺序),并为 遍历列表

因为它是一个接口,所以您只能通过its与
HTMLCollection
交互。那里没有修改对象的方法,只能读取对象。您必须以其他方式操作DOM

下面是一些使用纯JS的建议,但我强烈推荐使用此类任务。假设我们正在使用新元素
newDiv
HTMLCollection
文档。表单

在表单[1]之前插入

forms[1].parentNode.insertBefore(newDiv, forms[1]);
// there is no insertAfter() so use the next sibling as reference element
forms[1].parentNode.insertBefore(newDiv, forms[1].nextSibling);
forms[1].parentNode.replaceChild(newDiv, forms[1]);
在表单[1]之后插入:

forms[1].parentNode.insertBefore(newDiv, forms[1]);
// there is no insertAfter() so use the next sibling as reference element
forms[1].parentNode.insertBefore(newDiv, forms[1].nextSibling);
forms[1].parentNode.replaceChild(newDiv, forms[1]);
替换
表格[1]

forms[1].parentNode.insertBefore(newDiv, forms[1]);
// there is no insertAfter() so use the next sibling as reference element
forms[1].parentNode.insertBefore(newDiv, forms[1].nextSibling);
forms[1].parentNode.replaceChild(newDiv, forms[1]);

、和。

的文档和示例我尝试了很多方法…将集合转换为数组,然后继续,但这不符合我的目的。我可以从该集合中删除元素,但没有添加元素。也许可以在此处复制一些设置HTMLCollection的代码,并精确显示我建议在你的问题中加入一些代码,并明确指出你的困难所在。