Sunil Sunil - 6 months ago 70
Javascript Question

How to remove an item from HTMLCollection?

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

HTMLCollection is a live array-like object, that means if you need to remove an element from such collection, you will have to remove it from the DOM. You can always clone it into an Array for manipulations.

Comments