If statement isn't working for simple JavaScript toggle : <p>In the <code>resize()</code> function we check if the <code>body</code> element has the class <code>switch</code>. If it contains <code>switch</code> then we remove it when <code>resize</code> is fired. If it doesn't have the <code>switch</code> class then we add it when the function is fired. </p>

<p>However in the snippet below when the button is clicked it doesn't work as a toggle. It gets clicked only once and it's original state cannot be restored.</p>

<p>Why doesn't this simple JavaScript work and what are some ways to fix this?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function resize() {
  var body = document.querySelector( 'body' );
  
  if( body.classList.contains( 'switch' ) ){
    body.classList.remove( 'shrink' ); 
  }
  else {
    body.classList.add( 'shrink' ); 
  }
}

var switcher = document.getElementById( 'switch' );
switcher.addEventListener( 'click', resize );</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  text-align: center;
  margin-bottom: 1rem;
  transition-property: color;
  transition-duration: 1.5s;
}
.bar {
  width: 22.5rem;
  height: 10rem;
  background-color: #555;
  border-radius: 5rem;
  position: relative;
  transition-property: background-color;
  transition-duration: 1.5s;
}
.knob {
  width: 12rem;
  height: 12rem;
  background-color: #000;
  border-radius: 10rem;
  position: absolute;
  top: 50%;
  right: 0;
  transform: translateY( -50% );
  transition-property: right, background-color;
  transition-duration: 1s, 1.5s;
}
:checked ~ label p { color: #888 }
:checked ~ label .bar { background-color: #888 }
:checked ~ label .knob {
  background-color: #777;
  right: 10.5rem
}
.shrink { transform: scale( 0.8 ) }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;head&gt;
  &lt;style&gt;
    * { margin: 0 }
    html { font-size: 10px }
    html,
    body,
    main { height: 100% }
    body {
      transition-property: transform;
      transition-duration: 1s;
    }
    main {
      font-family: arial;
      font-size: 6rem;
      display: flex;
      text-transform: capitalize;
    }
    input { display: none }
    label,
    p {
      user-select: none;
      cursor: pointer;
      margin: auto;
    }
  &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;main&gt;
    &lt;input type="checkbox" id="checkbox"&gt;
    &lt;label for="checkbox" id="switch"&gt;
      &lt;p&gt;switch&lt;/p&gt;
      &lt;div class="bar"&gt;
        &lt;div class="knob"&gt;&lt;/div&gt;
      &lt;/div&gt;
    &lt;/label&gt;
  &lt;/main&gt;
&lt;/body&gt;</code></pre>
</div>
</div>
</p>
