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

编程入门 行业动态 更新时间:2024-10-24 23:17:07
本文介绍了如何在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 进行交互。 developer.mozilla/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中?

本文发布于:2023-11-22 19:13:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618664.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   元素   如何在   HTMLCollection   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!