title: Manipulate CSS classes with vanilla JavaScript
body: <p>Is there a way to manipulate a CSS class with plain JavaScript?</p>
  
  <p>I am creating a dropdown-menu and I want to transition it from <code>height: 0</code> to the computed height of the element when <code>height: auto</code>.</p>
  
  <p><strong>By default, the CSS class that I'm trying to manipulate does not have an element.</strong>
  <hr>
  <strong>HTML:</strong></p>
  
  <pre><code>&lt;ul class="dropdown-parent"&gt;
    &lt;li&gt;&lt;a&gt;Link&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;
      &lt;a&gt;Link&lt;/a&gt;
      &lt;ul class="dropdown"&gt;
        &lt;li&gt;Link&lt;/li&gt;
        &lt;li&gt;Link&lt;/li&gt;
        &lt;li&gt;Link&lt;/li&gt;
      &lt;/ul&gt;
    &lt;/li&gt;
  &lt;/ul&gt;
  </code></pre>
  
  <p><strong>CSS:</strong></p>
  
  <pre><code>.dropdown-parent {
      position: relative;
  }
  
  .dropdown {
      position: absolute;
      left: 0;
      top: 100%;
      height: 0;
      overflow: hidden;
      transition: height 1s ease-in-out;
  }
  
  .expand {}
  </code></pre>
  
  <p>JavaScript:</p>
  
  <pre><code>const dropdown = document.querySelector('.dropdown-parent');
  const dropdownList = document.querySelector('.dropdown');
  
  dropdownList.style.height = 'auto';
  const dropdownHeight = dropdownList.offsetHeight;
  dropdownList.style.height = '0';
  
  dropdown.addEventListener('click', () =&gt; {
      -- TRYING TO ADD CALCULATED HEIGHT TO THE CLASS '.expand' --
  
      dropdown.classList.toggle('expand');
  });
  </code></pre>
  
  <hr>
  
  <p><strong>I want to:</strong></p>
  
  <p>1) Fetch the element in the DOM.</p>
  
  <p>2) Set the element's height to auto.</p>
  
  <p>3) Calculate it's height and store it in a variable.</p>
  
  <p>4) Set it's height back to 0.</p>
  
  <p>5) Add the calculated height to the class <code>.expand</code>. </p>
  
  <p>6) Add an event listener to the parent to toggle the class <code>.expand</code>.</p>
  
  <p>The only thing I cannot do is the step (5).</p>
  
  <p>Some help on this topic?</p>