簡體   English   中英

如何將元素添加到 javascript 中的 HTMLCollection 中?

[英]How to add an element into the HTMLCollection in javascript?

我有一個 HTMLCollection Object,我可以用它來操作 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文檔

HTMLCollection是一個表示元素的通用集合的接口(按文檔順序),並提供遍歷列表的方法和屬性。

因為它是一個接口,所以你HTMLCollection通過它的方法HTMLCollection進行交互。 沒有方法可以修改對象,只讀它。 你必須以其他方式操縱DOM

以下是使用純JS的一些建議,但我強烈建議jQuery執行此類任務。 假設我們正在使用新元素newDivHTMLCollection document.forms

forms[1] 之前插入

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

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的文檔和示例。

您需要直接將新元素插入到 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>

正如您在上面看到的(與您使用 ie 時相反: const collItems = elParent.querySelectorAll(".item"); )實時 HTMLCollection 報告總共有 5 個子項。

此外,您還可以了解如何使用 append 並將項目添加為firstlast
回答你的另一個問題:

“如何在特定索引處插入”

您可以使用:

 // 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM