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]);
To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
HTMLCollection items can be accessed by their name, id, or index number. NodeList items can only be accessed by their index number. An HTMLCollection is always a live collection. Example: If you add a <li> element to a list in the DOM, the list in the HTMLCollection will also change.
An HTMLCollection is an array-like collection (list) of HTML elements. The elements in a collection can be accessed by index (starts at 0). The length Property returns the number of elements in the collection.
According to the MDN docs
HTMLCollection
is an interface representing a generic collection of elements (in document order) and offers methods and properties for traversing the list.
Because its an interface, you're restricted to interacting with an HTMLCollection
via 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 newDiv
and the HTMLCollection
document.forms
:
insert before forms[1]
:
forms[1].parentNode.insertBefore(newDiv, forms[1]);
insert after 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].parentNode.replaceChild(newDiv, forms[1]);
Documentation and examples for insertBefore(), replaceChild(), nextSibling, and parentNode.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With