加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

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

发布时间:2020-12-14 23:03:04 所属栏目:资源 来源:网络整理
导读:我有一个HTMLCollection对象,我可以用它来操纵HTMLCollection的内容.我想知道如何将div元素添加到HTMLCollection的第一个,最后一个或任何特定索引.请提出建议. 这里nDivs是HTML集合. var Div = document.createElement('div'); for(i=0; i 最佳答案 根据MDN

我有一个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.

因为它是一个接口,你只能通过它的methods与HTMLCollection交互.没有方法可以修改对象,只读它.你必须以其他方式操纵DOM.

以下是使用纯JS的一些建议,但我强烈建议jQuery执行此类任务.假设我们正在使用新元素newDiv和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的文档和示例.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读