0

Here is an Array of DOM elements, and I want to remove all those elements that have a certain class, in this case "checked-item". also I want to mutate the original array so I think filter method is out of the question.

taskArr = [some DOM Elements]
taskArr.forEach(function (task) {
 if (task.children[1].className.includes("checked-Item")) {
   taskArr.splice(taskArr.indexOf(task), 1);    
}
});
Usman-FE
  • 3
  • 1

2 Answers2

0

When a list is mutated while iterating, there can be side effects. The splice can cause the subsequent item to be skipped. This is one reason immutable functions like filter are much easier to reason about.

user650881
  • 2,214
  • 19
  • 31
0

Your error is probably because you splice elements inside loop, so if you console log the task, not every will be in output. I found an solution, without foreach:

taskArr = [some DOM Elements]
const length = taskArr.length;
var deleted = 0;
for(var i = 0; i < length; i ++){
     if(taskArr[i - deleted].children[1].className.includes("checked-Item")){
         taskArr.splice(i - deleted, 1);
          deleted ++;
     }
}
zhokya
  • 101
  • 6
  • 1
    Or you can loop from length to 0 in the reverse direction. You don't have to keep track of `deleted` in that case: [Looping through array and removing items, without breaking for loop](https://stackoverflow.com/questions/9882284) – adiga May 20 '21 at 07:13