问题描述
我有一个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]);
推荐答案
根据
因为它是一个接口,你只能通过其。没有方法可以修改对象,只读它。 你必须以其他方式操纵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的一些建议,但我强烈建议。假设我们正在使用新元素 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]);
,,,以及。
这篇关于如何在javascript中将元素添加到HTMLCollection中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!