goose goose
goose goose

Reputation: 96

Toggle add and remove class in JavaScript with if condition

I have a element with an id="caretToggle" and a button with onclick="caretToggle()". This fires a function that adds a class to invert the caret on the button.

I am successful in running:

function caretToggle() {
  var caretElement = document.getElementById("caretToggle");
  caretElement.classList.add("dropup");
}

But This leaves the caret inverted after the collapse is closed. I want to toggle the caret once the button is clicked again.

This is my condition code that I have failed to get working:

function caretToggle() {
  var caretElement = document.getElementById("caretToggle");
  if (caretElement.classList.contains("dropup")) {
    caretElement.classList.remove("dropup");
  } else {
    caretElement.classList.add("dropup");
  }
}

Thank you in advance for any help you may provide!

Upvotes: 1

Views: 4307

Answers (2)

German
German

Reputation: 1166

If you want to toggle class simply do it like this

let caretElement = document.getElementById("caretToggle");
    function caretToggle() {
      caretElement.classList.toggle("dropup");
      console.log('class attribute contains: ', caretElement.className)
    }
span {
margin:10px;
}


.dropup {
  background-color: purple;
  padding: 1em;
  border-radius: 10px;
  color: white;
}
<span id="caretToggle">HTMLElement</span>
<br/>
<br/>
<br/>
<br/>
<button onclick="caretToggle()">Click</button>

Upvotes: 0

halilcakar
halilcakar

Reputation: 1648

You dont need to check wheter contains or not. What you can do simply use toggle function on classList :)

function caretToggle() {
  var caretElement = document.getElementById("caretToggle");
  caretElement.classList.toggle("dropup");
}

And also there is a conditional toggle like:

caretElement.classList.toggle("dropup", counter < 10)

Check here from MDN

Upvotes: 3

Related Questions