MDN self-hosted library · e01.org

DOMTokenList: toggle() method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

html
<span class="a b">classList is 'a b'</span>
js
const span = document.querySelector("span");
const classes = span.classList;

span.addEventListener("click", () => {
  const result = classes.toggle("c");
  span.textContent = `'c' ${
    result ? "added" : "removed"
  }; classList is now "${classes}".`;
});
js
span.classList.toggle("c", window.innerWidth > 1000);