How to add an element to an HTMLCollection in javascript?

I have an HTMLCollection object that I can use to manage the contents of an HTMLCollection. I would like to know a way out to add a div element to the first, last or to any particular HTMLCollection index. Please suggest something. Here nDivs is an 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]);
+5
source share
1 answer

According to MDN docs

HTMLCollection - This is an interface that represents a common set of elements (in document order) and offers methods and properties for moving the list.

HTMLCollection methods. , . DOM - .

JS, jQuery . , newDiv HTMLCollection document.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(), nextSibling parentNode.

+9

All Articles