Good day. There is a menu button

`<div class="grid__menu"> <i class="material-icons md-48 menu__button">dashboard</i> </div>` 

when I click on that, I want to change the menu__button class to menu__button--active can change the class menu__button

  var activeModificator = '--active'; function toggle (className, active) { var name = className.replace(/\./g, ''); var activeName = (active === undefined) ? activeModificator : active; if (name.indexOf(activeName) == -1) { document.querySelector(className).classList.add(name+activeModificator); document.querySelector(className).classList.remove(name); } else { document.querySelector(className).classList.add(name); document.querySelector(className).classList.remove(name-activeModificator); } } 

But in the function I need to pass the name of the class, which must be taken from the line <i class="material-icons md-48 menu__button">dashboard</i>

How do I get the class name from document.querySelector(".menu__button"); ? After all, there will first be menu__button , and then menu__button--active ? And after the first change the class will be different. What is the algorithm at all? No jQuery

JsFiddle example

  • "After all, there will first be menu __button, and then menu __button?" - HamSter
  • Corrected, sorry - Slip
  • updated the answer .. - Jean-Claude

1 answer 1

The solution is typical, updated

 document.querySelector('.grid__menu i').addEventListener('click', function() { classToggle('menu__button', '--active', this); }, false) function classToggle(a, b, elem) { console.log(elem); elem.classList.remove(a); elem.classList.add(a + b); } 
 .menu__button { border: 2px solid red; } .menu__button--active { border: 2px solid green; background-color: yellow; } 
 <div class="grid__menu"> <i class="material-icons md-48 menu__button">dashboard</i> </div> 

  • And if I don’t have <div class = "grid__menu">? Is it possible to somehow pull out the existing classList? - Slip
  • And by the way, this code does not change back the next time you click. Those. no toggle coming out. Anyway thanks, of course - Slip