0

My original code but the letter 'i' received a message as undefined.
original code.

function buttonRed {

  for (let i=0; i < all_buttons.length; i++)  {
   all_buttons[i].classList.remove(all_buttons[i].classList[1];
   all_buttons[i].classList.add(all_buttons[i].classList[1];
   all_buttons[i].classList.add('btn-danger');
}
    

console.log stated "i" was not defined. I then changed "let" to "var" in the line of code and now console.log says cannot read property of classList of undefined.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I suspect you misread the message. It didn't say that `i` was undefined, it said that `all_buttons[i]` was undefined. – Barmar Sep 07 '21 at 19:24
  • 2
    How are you creating `all_buttons`? If it's from `document.getElementsByClassName()`, the list changes when you change the classes. – Barmar Sep 07 '21 at 19:25
  • 1
    You are also missing closing `)` in your first 2 statements – LeeLenalee Sep 07 '21 at 19:25
  • See https://stackoverflow.com/questions/29587769/classname-only-changing-every-other-class – Barmar Sep 07 '21 at 19:25

1 Answers1

0

Here's a snippet with fixed syntax. I added inline comments for explanation.

function buttonRed() { // function declaration need parenthesis

  for (let i=0; i < all_buttons.length; i++)  {
   all_buttons[i].classList.remove(all_buttons[i].classList[1]); // missing closing )
   all_buttons[i].classList.add(all_buttons[i].classList[1]); // missing closing )
   all_buttons[i].classList.add('btn-danger');
  }

} // missing ending bracket for function definition
Alex Gyoshev
  • 11,929
  • 4
  • 44
  • 74