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]);
According to the MDN docs
Because its an interface, you’re restricted to interacting with an
HTMLCollectionvia 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.Here are some suggestions using pure JS, but I highly recommend jQuery for such tasks. Assume we’re working with a new element
newDivand theHTMLCollectiondocument.forms:insert before
forms[1]:insert after
forms[1]:replace
forms[1]:Documentation and examples for insertBefore(), replaceChild(), nextSibling, and parentNode.