• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Miscellaneous / Vanilla JS toggle

Vanilla JS toggle

Vanilla JS toggle
const span = document.querySelector("span");
let classes = span.classList;

span.addEventListener("click", function() {
  let result = classes.toggle("active");

  if (result) {
    console.log("active class was added");
  } else {
    console.log("active class was removed");
  }
});

Source

https://github.com/roeib/JavaScript-snippets#vanilla-js-toggle

Miscellaneous

Related Snippets:

  • Check if the user color scheme preference is dark
  • Check if a string is a valid JSON
  • Looping over an object’s keys and values
  • Filter out matching array elements

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers