How to remove an item from HTMLCollection?
Asked Answered
B

7

9

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
        }
    }
Behavior answered 18/5, 2016 at 22:17 Comment(15)
That first semi-colon in the for loop seems kinda out of place...Actinometer
@bjskistad Looks right to me.Tejada
@bjskistad, I am looping backwards since I want to remove items from the collection.Behavior
A native HTMLCollection is not an array, it doesn't have a splice method, and elements can't be removed or added unless you actually remove or add them to the DOM. You probably want to convert it to an array.Manama
@Derek朕會功夫 I'm not the biggest fan of JavaScript. Probably works, I code in Python, so spaces matter a lot to me, probably doesn't matter in JS.Actinometer
Convert the collection to an array if you want to use Array methods, such as splice (); use array.from(allInputs) for example.Beograd
@Behavior I'm just talking about the space before the semi-colon, I'm just wondering if that is grammatically correct.Actinometer
@bjskistad - doesn't matter, spaces generally mean nothing.Manama
@bjskistad: yes, that white-space is fine.Beograd
@Manama Ok, as I mentioned, I'm not the biggest JS guy. :PActinometer
@bjskistad, As already mentioned space will not matter in this case.Behavior
For full browser support -> [].slice.call(allInputs)Manama
"but not sure if there is any other shorter way of doing this." There isn't.Moiety
@adeneo, Is [] in [].slice.call(allInputs) the HTMLCollection?Behavior
@Behavior - no, it's Array.prototypeManama
B
8

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.

Betook answered 18/5, 2016 at 22:25 Comment(0)
B
17

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.

Brody answered 18/5, 2016 at 22:52 Comment(0)
B
8

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.

Betook answered 18/5, 2016 at 22:25 Comment(0)
D
5

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;
Donn answered 10/10, 2018 at 13:37 Comment(0)
F
4

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

Footlights answered 4/5, 2017 at 10:2 Comment(0)
P
2

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)
Polston answered 17/8, 2017 at 9:53 Comment(0)
N
1

You can use Array.from, to transform the HTML collection into a array and then use the splice.

var allInputs = contentElement.getElementsByTagName('input');
allInputs = Array.from(allInputs)
    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
        }
    }
Nonparticipating answered 11/7 at 20:11 Comment(0)
S
0

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}).

Supernumerary answered 20/9, 2021 at 11:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.