I would like to do a simple loop using document querySelectorALL
and loop through the list that is returned. Within the loop, I checked other references which declare the loop using (var i = 0; i < btns.length; i++)
. This gave me the following error:
Uncaught TypeError: Cannot read properties of undefined (reading ‘style’) at HTMLButtonElement.onClick
But when I changed var
to let
, it works.
Can’t figure out why.
<script>
// TODO: Add code to check answers to
const btns = document.querySelectorAll('button');
for (let i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function onClick() {
btns[i].style.backgroundColor = 'red';
});
}
</script>