title: Toggle add and remove class in JavaScript with if condition
body: <p>I have a element with an id=&quot;caretToggle&quot; and a button with onclick=&quot;caretToggle()&quot;. This fires a function that adds a class to invert the caret on the button.</p>
  <p>I am successful in running:</p>
  <pre><code>function caretToggle() {
    var caretElement = document.getElementById(&quot;caretToggle&quot;);
    caretElement.classList.add(&quot;dropup&quot;);
  }
  </code></pre>
  <p>But This leaves the caret inverted after the collapse is closed. I want to toggle the caret once the button is clicked again.</p>
  <p>This is my condition code that I have failed to get working:</p>
  <pre><code>function caretToggle() {
    var caretElement = document.getElementById(&quot;caretToggle&quot;);
    if (caretElement.classList.contains(&quot;dropup&quot;)) {
      caretElement.classList.remove(&quot;dropup&quot;);
    } else {
      caretElement.classList.add(&quot;dropup&quot;);
    }
  }
  </code></pre>
  <p>Thank you in advance for any help you may provide!</p>