简体   繁体   English

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

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

I have an HTMLCollection Object which i can use to manipulate the content of the HTMLCollection.我有一个 HTMLCollection Object,我可以用它来操作 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.我想知道将 div 元素添加到 HTMLCollection 的第一个、最后一个或任何特定索引的方法。 Please suggest something.请提出一些建议。 Here nDivs is the HTML Collection.这里 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]);

According to the MDN docs 根据MDN文档

HTMLCollection is an interface representing a generic collection of elements (in document order) and offers methods and properties for traversing the list. HTMLCollection是一个表示元素的通用集合的接口(按文档顺序),并提供遍历列表的方法和属性。

Because its an interface, you're restricted to interacting with an HTMLCollection via its methods . 因为它是一个接口,所以你HTMLCollection通过它的方法HTMLCollection进行交互。 There are no methods there to modify the object, only to read it. 没有方法可以修改对象,只读它。 You'll have to manipulate the DOM some other way . 你必须以其他方式操纵DOM

Here are some suggestions using pure JS, but I highly recommend jQuery for such tasks. 以下是使用纯JS的一些建议,但我强烈建议jQuery执行此类任务。 Assume we're working with a new element newDiv and the HTMLCollection document.forms : 假设我们正在使用新元素newDivHTMLCollection document.forms

insert before forms[1] : forms[1] 之前插入

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

insert after 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);

replace forms[1] : 替换 forms[1]

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

Documentation and examples for insertBefore() , replaceChild() , nextSibling , and parentNode . insertBefore()replaceChild()nextSiblingparentNode的文档和示例。

You need to insert your new Elements in the DOM directly.您需要直接将新元素插入到 DOM 中。 You cannot manipulate a read-only HTMLCollection directly.您不能直接操作只读的 HTMLCollection。 But don't worry, your HTMLCollection (stored in a variable) will update accordingly:但别担心,您的 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>

as you can see above (contrary to if you used ie: const collItems = elParent.querySelectorAll(".item"); ) the live HTMLCollection reports that is has 5 children in total.正如您在上面看到的(与您使用 ie 时相反: const collItems = elParent.querySelectorAll(".item"); )实时 HTMLCollection 报告总共有 5 个子项。

Also, you can see how to append and prepend an item as first or last .此外,您还可以了解如何使用 append 并将项目添加为firstlast
To answer your other question:回答你的另一个问题:

"how to insert at a specific index" “如何在特定索引处插入”

you can use:您可以使用:

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

相关问题 如何将 eventListener 添加到 htmlCollection 中以更改另一个元素的显示? - How do you add an eventListener to a htmlCollection that will change the display of another element? 如何使用javascript检查HTMLCollection是否包含具有给定类名的元素? - How to check if an HTMLCollection contains an element with a given class name using javascript? 如何在HTMLCollection或Element上使Javascript Cals /构造函数可调用 - How to make Javascript calss/constructor callable on HTMLCollection or Element 如何在JavaScript中检测HTMLCollection / NodeList? - How to detect HTMLCollection/NodeList in JavaScript? 如何在 Javascript 中遍历 HTMLCollection - How to iterate through HTMLCollection in Javascript JavaScript HtmlCollection循环从不返回第二个元素 - JavaScript HtmlCollection loop never returns second element 如何动态地将类添加到HTMLCollection(将HTMLCollection转换为数组的问题)? - How to dynamically add a class to an HTMLCollection (problem converting HTMLCollection into an array)? JavaScript我如何遍历HTMLcollection中的每个当前和将来的元素? - JavaScript how do i iterate over every current and future element in a HTMLcollection? 如何在Javascript / Babel中迭代HTMLCollection - How to iterate through HTMLCollection in Javascript/Babel 如果满足条件,则尝试在HTMLCollection中的项目后添加元素 - Trying to add an element after an item in an HTMLCollection if criteria is met
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM