+ 3
getElementsByClassName not getting all elements ?
Can someone help me find why not all the hexagons are removed from the screen. I cannot find where my mistake is. It seems like getElementsByClassName does not get ALL elements... The interesting thing is that I always get the same pattern left. window.onclick = () => { var hexs = svg.getElementsByClassName('hex'); for(var hex of hexs){ svg.removeChild(hex); } } https://code.sololearn.com/WW5W4vgeBAEv/?ref=app
1 Odpowiedź
+ 4
Ok looks like I removed one hex on two.
Looks like my 'hexs' array was updating live.
Let's say that I begin with hexs = [hex1, hex2, hex3, hex4]
I start with i=0 and remove hex1 from my svg,
then it appears that hexs no longer is [hex1, hex2, hex3, hex4] but [hex2, hex3, hex4]
so when I go to i = 2 and remove from svg, I don't remove hex2 but hex3 instead...
So I remove one on two only.
Still don't know exactly how I linked my array with my svg.
I found this code that works :
while(hexs.length>0){
svg.removeChild(hexs[0]);
hexs = svg.getElementsByClassName('hex');
}
this is an other solution :
for(var i=hexs.length; i>0; i--){
svg.removeChild(hexs[i-1]);
}
Updated my code with the solution.