Home » Javascript » Adding and removing class from HTML elements in ES6 / ES7

Adding and removing class from HTML elements in ES6 / ES7

Posted by: admin August 19, 2018 Leave a comment

Questions:

I have the following code in which I have some HTML button elements.

I want that whenever I click a button, class selected should toggle in that button.

Here is the code:

window.onload = function() {
  const [...btns] = document.getElementsByTagName('button');
  
  for(let i = 0; i < btns.length; i++) {
    btns[i].addEventListener('click', function() {
      if(this.className.split(' ').indexOf('selected') > -1) {
        this.className = this.className.split(' ').pop();
      } else {
        this.className = this.className.split(' ').push('selected').join(' ');
      }
      
      console.log(this.className);
    });
  }
}
button {
  outline: none;
  border: none;
  padding: 3px 7px;
  color: #FF4A3F;
  background: #E7E7E7;
  font: 500 16pt calibri;
  transform: scale(1, 0.95);
}
.selected {
  background: #353553;
  color: white;
}
<button>Home</button>
<button>Admission</button>
<button>Results</button>
<button>Curriculum</button>
<button>Contact us</button>
Answers: