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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8856281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:47:54  来源:igfitidea点击:

How to add an element into the HTMLCollection in javascript?

javascripthtml

提问by Ruchir

I have an HTMLCollection Object which i can use to manipulate the content of the HTMLCollection. I would like to know the way out to add a div element to the first, last or to any specific index of the HTMLCollection. Please suggest something. Here nDivs is the HTML Collection.

我有一个 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]);

回答by paislee

According to the MDN docs

根据MDN 文档

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

HTMLCollection是一个接口,表示元素的通用集合(按文档顺序),并提供遍历列表的方法和属性。

Because its an interface, you're restricted to interacting with an HTMLCollectionvia its methods. There are no methods there to modify the object, only to read it. You'll have to manipulate the DOM some other way.

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

Here are some suggestions using pure JS, but I highly recommend jQueryfor such tasks. Assume we're working with a new element newDivand the HTMLCollectiondocument.forms:

这里有一些使用纯 JS 的建议,但我强烈推荐jQuery用于此类任务。假设我们正在处理一个新元素newDiv,并且HTMLCollectiondocument.forms

insert beforeforms[1]:

在之前插入forms[1]

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

insert afterforms[1]:

插入后forms[1]

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

replaceforms[1]:

替换forms[1]

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

Documentation and examples for insertBefore(), replaceChild(), nextSibling, and parentNode.

insertBefore()replaceChild()nextSiblingparentNode 的文档和示例。