Skip to content
Advertisement

My JavaScript isn’t changing className property

Here is the main part of my code attempting to toggle class on a p tag (info) on click of my button (btn). I’m not sure what I’m doing wrong. I have never used the className property before so I’m not sure if I’m missing something simple, or if there is fundamental error in my logic trying to attempt this.

var handler = function(event){
  if(info.className === 'on'){
    info.className='off';
  }else{
    info.className='on';
  }
};

btn.addEventListener('click', handler);

Advertisement

Answer

Your code works just fine. You can run the snippet below to see that it works.

var btn = document.getElementById("btn"),
    info = document.getElementById("info");

var handler = function (event) {
    if (info.className === 'on') {
        info.className = 'off';
    } else {
        info.className = 'on';
    }
};

btn.addEventListener('click', handler);
.on {
    background-color: red;
}
.off {
    background-color: green;
}
<button id=btn>Button</button>
<p id=info>Info</p>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement