简体   繁体   中英

Add and remove a class in javascript

I'm trying to write a function, to make a visual object come on and off, on and off, as the user clicks on it. Then add a click event listener in the class, called button btn-sauce .

So far my code doesn't work :

function renderWhiteSauce() {
  if (element.classList) {
  element.classList.toggle("btn-sauce.active");
} else {
  var classes = element.className.split(" ");
  var i = classes.indexOf("btn-sauce.active");
  if (i >= 0)
    classes.splice(i, 1);
  else
    classes.push("btn-sauce.active");
    element.className = classes.join(" ");
}

document.querySelector('.btn-sauce.active').addEventListener('click', () => {
  state.sauce = !state.sauce;
  renderEverything();
});

You can just add and remove classes with methods classList.add('classname') and classList.remove('classname'). Define class which makes btn active and just add or remove it.

const elem = document.querySelector('.btn-sauce')
elem.addEventListener('click', () => { 
 if(elem.className.indexOf('className') < 0) {
   elem.classList.add('className')
 } else {
   elem.classList.remove('className')
 }  
 });

btn-sauce and active are two separate classes, but you are writing your code like they are one. Remove btn-sauce. (including the dot) from everything above the querySelector line and you will be able to toggle the active class on and off.

If the element is not "active" to begin with, you should also change document.querySelector('.btn-sauce.active') to document.querySelector('.btn-sauce') .

One last note, you are calling renderEverything() in your click handler, which I assume is another function that calls renderWhiteSauce() , but I thought I'd mention it in case this was just a typo and they were meant to be the same function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM