如何在javascript中将元素添加到HTMLCollection中? [英] How to add an element into the HTMLCollection in javascript?

查看:208
本文介绍了如何在javascript中将元素添加到HTMLCollection中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTMLCollection对象,可用于操作HTMLCollection的内容。我想知道如何将div元素添加到HTMLCollection的第一个,最后一个或任何特定索引。请提出建议。
这里nDivs是HTML集合。

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.

    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 是一个表示
元素的通用集合的接口(按文档顺序),并提供遍历列表的
的方法和属性。

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

因为它是一个接口,你只能通过其 HTMLCollection 进行交互。 https://developer.mozilla.org/en/DOM/HTMLCollection#Methodsrel =noreferrer>方法。没有方法可以修改对象,只读它。 你必须以其他方式操纵DOM

Because its an interface, you're restricted to interacting with an HTMLCollection via 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.

以下是使用纯JS的一些建议,但我强烈建议 jQuery 。假设我们正在使用新元素 newDiv HTMLCollection document.forms

Here are some suggestions using pure JS, but I highly recommend jQuery for such tasks. Assume we're working with a new element newDiv and the HTMLCollection document.forms:

之前插入表单[1]

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

表格后插入[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中将元素添加到HTMLCollection中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆