How to remove an item from HTMLCollection?

Sunil picture Sunil · May 19, 2016 · Viewed 13.8k times · Source

I have some Javascript code to remove an item from a HTMLCollection as in code below. I get an error when splice is called that says: allInputs.splice is not a function. I need to remove items from HTMLCollection if the element type is not of button type.

Question : How would I remove an item from such a collection?

I could transfer undeleted items to an array and then I could work with the array instead of original HTMLCollection but not sure if there is any other shorter way of doing this.

JavaScript code

    var allInputs = contentElement.getElementsByTagName('input');
    for (var i = (allInputs.length - 1) ; i >= 0; i--) {
        if (allInputs[i].type !== "button") {
            allInputs.splice(i, 1);//this is throwing an error since splice is not defined
        }
    }

Answer

RobG picture RobG · May 19, 2016

You need to remove it from the DOM, so replace:

allInputs.splice(i, 1);

with:

allInputs[i].parentNode.removeChild(allInputs[i])

which is compatible wilth even ancient browsers like IE 6. The collection will update automatically. Iterating over the collection in reverse is a good idea as each time you remove a member, it will get shorter.

Note that:

[].slice.call(allInputs)

will fail in browsers like IE8 that do not allow host objects to be this in built–in methods.