gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:36:12 26 4
gpt4 key购买 nike

我有一个 HTMLCollection 对象,我可以用它来操作 HTMLCollection 的内容。我想知道将 div 元素添加到 HTMLCollection 的第一个、最后一个或任何特定索引的方法。请提出一些建议。这里的 nDivs 是 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]);

最佳答案

根据MDN docs

HTMLCollection is an interface representing a generic collection of elements (in document order) and offers methods and properties for traversing the list.

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

这里有一些使用纯 JS 的建议,但我强烈推荐 jQuery对于这样的任务。假设我们正在使用一个新元素 newDivHTMLCollection document.forms:

插入 forms[1]:

forms[1].parentNode.insertBefore(newDiv, forms[1]);

forms[1] 之后插入:

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

替换 表单[1]:

forms[1].parentNode.replaceChild(newDiv, forms[1]);

insertBefore() 的文档和示例, replaceChild() , nextSibling , 和 parentNode .

关于javascript - 如何在 javascript 中将元素添加到 HTMLCollection 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8856281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com