How do I toggle an element's class in pure JavaScript?

max imax picture max imax · Sep 18, 2013 · Viewed 145.3k times · Source

I'm looking for a way to convert this jQuery code (which is used in responsive menu section) to pure JavaScript.

If it's hard to implement it's OK to use other JavaScript frameworks.

$('.btn-navbar').click(function()
{
    $('.container-fluid:first').toggleClass('menu-hidden');
    $('#menu').toggleClass('hidden-phone');

    if (typeof masonryGallery != 'undefined') 
        masonryGallery();
});

Answer

mikemaccana picture mikemaccana · Apr 16, 2014

2014 answer: classList.toggle() is the standard and supported by most browsers.

Older browsers can use use classlist.js for classList.toggle():

var menu = document.querySelector('.menu') // Using a class instead, see note below.
menu.classList.toggle('hidden-phone');

As an aside, you shouldn't be using IDs (they leak globals into the JS window object).