我有一个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中?
发布评论