For Loop Skips First Item In Array
Solution 1:
Splice causes the members of the array to be re–indexed, so the loop skips the next member. To avoid that, iterate from the end to the start. If you want to maintain order in the result array, use unshift instead of push.
Also, you're adding the remove class after splicing the member from the array, so it get's added to the following member. So add it before splicing.
var all = [];
var newall = [];
var list = document.body.getElementsByTagName('*');
var i = j = list.length;
while (i--) {
all[i] = list[i];
}
while (j--) {
if(all[j].classList.contains('div')) {
// add class before removing
all[j].classList.add('remove');
all.splice(j, 1);
} else {
// Since iterating backwards, add members to start of newall// with unshift rather than end with push
newall.unshift(all[j]);
all[j].classList.add('keep');
}
}
.remove {text-decoration: line-through;}
.keep {background: yellow;}
<divid="alpha"class="div one">alpha</div><pid="bravo"class="div two">bravo</p><divid="charlie">charlie</div>
Oh, and creating newall seems redundant as it will contain the same members as all.
Solution 2:
The problem is, once you splice the element the value of j
should not be incremented.
Assuming you are removing the item in index 1(j=1) and array has a length of 3, once you splice it the array length becomes 2 and the value at index 2 is now at index 1. In the next iteration you are incrementing the value of j to 2 now the loop condition fails and the last iteration fails to execute.
var list;
var all = [];
var newall = [];
list = document.body.getElementsByTagName('*');
for (var i = 0; i < list.length; i++) {
all.push(list[i]);
}
for (var j = 0; j < all.length; j++) {
if (all[j].classList.contains('div')) {
all[j].classList.add('remove');
all.splice(j, 1);
j--
} else {
newall.push(all[j]);
all[j].classList.add('keep');
}
}
.remove {
text-decoration: line-through;
}
.keep {
background: yellow;
}
<divid="alpha"class="div one">
alpha
</div><pid="bravo"class="div two">
bravo
</p><divid="charlie">
charlie
</div>
Post a Comment for "For Loop Skips First Item In Array"