0

I'm learning new loop structures in JS and I can't get a while loop to make changes to elements in the way I can with a for loop.

In the following code it throws an error 'Cannot set property 'background' of undefined'. This seems to be in relation to the variable mydiv?

Does anyone have an inclining as to why this might be or what is going on here?

JS

var mydiv = document.getElementsByTagName('div');

var i = 0;

while (i < mydiv.length) {
 mydiv.style.background = "yellow";
 i++;
}

CSS

body {display: flex;}
.box {width: 100px; height: 100px; background: red; margin: 0 
10px;}

HTML

<div class="box"></div>
<div class="box"></div>
pjk_ok
  • 618
  • 7
  • 35
  • 90

1 Answers1

1

you need to access the element by index inside the loop

var mydiv = document.getElementsByTagName('div');

var i = 0;

while (i < mydiv.length) {
 mydiv[i].style.background = "yellow";
 i++;
}
klugjo
  • 19,422
  • 8
  • 57
  • 75