'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
}
}
Solution 1:[1]
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.
Solution 2:[2]
It is actually possible to do this, you just need to push the elements you want into another HTMLCollection, then set the original collection to the new collection (or just use the new collection)
var allInputs = contentElement.getElementsByTagName('input');
var inputsWeActuallyWant = [];
for (var i = (allInputs.length - 1) ; i >= 0; i--) {
if (allInputs[i].type === "button") {
inputsWeActuallyWant.push(allInputs[i]);
}
}
allInputs = inputsWeActuallyWant;
Solution 3:[3]
To remove an newly created img from HTMLCollection images I'd uset next string
img.ownerDocument.images[img.index].remove()
where img.index was defined on creation
Solution 4:[4]
You can also use Array.splice. However, the length property of HTMLCollections is read-only, so in order to use an Array method like splice, you have to explicitly make it writable beforehand:
Object.defineProperty(allInputs, 'length', {
writable: true
})
Array.prototype.splice.call(allInputs, i, 1)
Solution 5:[5]
Use
var allInputs = contentElement.getElementsByTagName('input');
let newArr = []
let i = 0;
while(i<allInputs.length){
//Add Your Filter Here
if (allInputs[i].type !== "button") {
//skip this Item
i++;
}else{
//add it
newArr.push(allInputs[i])
//code..
i++;
}
}
Your New List is newArr :)
after that you can use newArr.forEach(function(el){//code here}).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RobG |
| Solution 2 | shakyjake |
| Solution 3 | |
| Solution 4 | Gust van de Wal |
| Solution 5 |
