Home>

Below is the code to switch the class'Open' when id = "menu" is clicked,
If class = "menu", how can it be rewritten?

For classes, using getElementsByClassName is
I found it somehow, but I couldn't find it even after searching.
Isn't it highly recommended?

const Menu = document.getElementById ('menu');
Menu.addEventListener ('click', () =>{
Menu.classList.toggle ('Open');
});
  • Answer # 1

    getElementsByClassName returns multiple elements (HTMLCollection), so you need to loop through the for statement.

    const menus = document.getElementsByClassName ('menu');
    for (let i = 0;i<menus.length;i ++) {
      menus [i] .addEventListener ('click', () =>{
        menus [i] .classList.toggle ('Open');
      }, false);
    }

Related articles