• 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 / CSS / Add, remove, toggle, and check for the presence of a class

Add, remove, toggle, and check for the presence of a class

Add, remove, toggle, and check for the presence of a class.

Here are some handy, simple ways to manipulate CSS classes.

var elem = document.querySelector('#sandwich');

// Add a class
elem.classList.add('turkey');

// Remove a class
elem.classList.remove('tuna');

// Toggle a class
// (Add the class if it's not already on the element, remove it if it is.)
elem.classList.toggle('tomato');

// Check if an element has a specific class
if (elem.classList.contains('mayo')) {
	console.log('add mayo!');
}

Source

https://vanillajstoolkit.com/reference/classes/classlist/

CSS

Related Snippets:

  • Toggle a class for an HTML element
  • Add a Class to an Element
  • Selecting Elements By Class Name
  • Get all of an element’s parent elements up the DOM tree

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