toggle css class

hey,

i have the following code:

li3.getElement().addEventListener("click", e -> {
  li3.getElement().getClassList().set("opened", true);
}

li3 is a html “

  • ” element.

    if this “li3” gets clicked, i want to add the class “opened” to it. and if you click it again, i want the class “opened” to be removed. with this code the class “opened” gets added, but i dont know what to do to get it removed again on another click. (i basically want a toggle)

  • ClassList extends from Set, so you should be able to use it’s methods to check for existing values and then either add or remove:

    ClassList classList = li3.getElement().getClassList();
    if (classList.contains("opened")) {
        classList.remove("opened");
    } else {
        classList.add("opened");
    }
    

    thank you so much!