Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

Toggle class – JavaScript

Length: 10 minutes

Summary

let element = document.querySelector('#id-name');
element.classList.toggle('class-name');

Details

To toggle a CSS class on an element, you’ll first want to select an element using querySelector() and save it to a variable. Replace #id-name with the actual selector you want to use.

let element = document.querySelector('#id-name');

Next, you’ll want to use the classList and the toggle() function to add a class name. Replace class-name with the actual class name you want to use (and make sure the class already exists in your CSS code).

let element = document.querySelector('#id-name');
element.classList.toggle('class-name');

Demo

Exercises

Recreate the JS code from the Demo section in your JS file.

Reference

classList on MDN

Back to: JavaScript Reference > JS DOM