Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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]);
like image 942
Ruchir Avatar asked Jan 13 '12 19:01

Ruchir


People also ask

How do you add an element to the DOM?

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.

How do you manipulate HTMLCollection?

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.

How do you access an element in HTMLCollection?

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.


1 Answers

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.

like image 114
calebds Avatar answered Sep 30 '22 20:09

calebds