Home  >  Article  >  Web Front-end  >  How to Toggle Element Classes Dynamically Using Pure JavaScript?

How to Toggle Element Classes Dynamically Using Pure JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-21 12:01:30119browse

How to Toggle Element Classes Dynamically Using Pure JavaScript?

Toggling Element Classes in Pure JavaScript: A Simplified Guide

The task of modifying element classes dynamically can be achieved using pure JavaScript. This process eliminates the need for additional frameworks or libraries like jQuery.

jQuery Conversion:

Consider the following jQuery snippet:

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

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

Pure JavaScript Implementation:

To achieve the same functionality in pure JavaScript, the classList.toggle() method is commonly used. This method is supported by most modern browsers.

var menu = document.querySelector('.menu');  // Using a class instead of an ID
menu.classList.toggle('hidden-phone');

Note: Using IDs in JavaScript can lead to global leakage and is generally not recommended.

ClassList.js for Older Browsers:

For browsers that do not natively support classList.toggle(), you can incorporate the classlist.js polyfill.

var menu = document.querySelector('.menu');
menu.classList.toggle('hidden-phone');

This implementation reliably toggles classes without the need for external libraries or frameworks, providing a concise and efficient approach in pure JavaScript.

The above is the detailed content of How to Toggle Element Classes Dynamically Using Pure JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn