如何在JavaScript中向HTMLCollection添加元素?

16

我有一个 HTMLCollection 对象,可以用它来操作 HTMLCollection 的内容。我想知道如何向 HTMLCollection 的第一个、最后一个或任何指定索引添加一个 div 元素。请给出建议。这里 nDivs 是 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]);

我尝试了很多方法...将集合转换为数组然后进行操作,但这并不能满足我的需求。我能够从该集合中删除一个元素,但添加一个元素却没有发生。 - Ruchir
也许在这里复制一些设置你的HTMLCollection的代码,并展示你想要的内容。 - cambraca
我建议在你的问题中包含一些代码,并明确指出你的困难所在。 - calebds
2个回答

26
根据MDN文档HTMLCollection是一个表示元素集合的通用接口(按文档顺序),提供了遍历列表的方法和属性。

HTMLCollection是一个接口,只能通过其方法与之交互。这里没有修改对象的方法,只能读取它。你需要用其他方式操作DOM

以下是一些使用纯JS的建议,但我强烈推荐jQuery来完成此类任务。假设我们正在处理一个新元素newDivHTMLCollectiondocument.forms

forms[1]之前插入

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

forms[1]后插入:

// there is no insertAfter() so use the next sibling as reference element
forms[1].parentNode.insertBefore(newDiv, forms[1].nextSibling);

替换 forms[1]:

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

介绍和示例:insertBefore()replaceChild()nextSiblingparentNode


如果forms已经是父节点,为什么要使用forms[1].parentNode.insertBefore(...)而不是简单地使用forms.insertBefore(...) - BitTickler

0
你需要直接将新的元素插入到DOM中。 你不能直接操作只读的HTMLCollection。 但不用担心,你的HTMLCollection(存储在变量中)将相应更新:

// DOM helper functions:
const el = (sel, par) => (par || document).querySelector(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);


// Cache a reference to the wrapper parent Element 
const elParent = el("#parent-a");

// Cache a live HTMLCollection:
const collItems = elParent.children;

// Insert new elements in the DOM:
elParent.prepend(elNew("div", {textContent: "Item First (New)"}));
elParent.append(elNew("div", {textContent: "Item Last (New)"}));

// Check if the collection is live:
console.log(collItems.length); // 5
<div id="parent-a">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>

正如您可以看到的那样(与使用const collItems = elParent.querySelectorAll(".item");相反),实时HTMLCollection报告总共有5个子项。

此外,您还可以看到如何将项目附加和预置为第一个最后一个
回答您的另一个问题:

"如何在特定索引处插入"

您可以使用:

// DOM helper functions:
const el = (sel, par) => (par || document).querySelector(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
const insertAtIndex = (idx, parent, ...els) => {
  els = els.flat();
  const ch = parent.children;
  if (idx >= ch.length) parent.append(...els);
  else ch[Math.max(idx, 0)].before(...els);
};

// Cache a reference to the wrapper parent Element 
const elParent = el("#parent-a");
// Cache a live HTMLCollection:
const collItems = elParent.children;
// Insert element/s at index
insertAtIndex(
  2,
  elParent,
  elNew("div", {textContent: "NEW item 1"}),
  elNew("div", {textContent: "NEW item 2"}),
);

console.log(collItems.length); // 4
<div id="parent-a">
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接