Home > Web Front-end > JS Tutorial > body text

How to Toggle Element Classes Dynamically Using Pure JavaScript?

Barbara Streisand
Release: 2024-10-21 12:01:30
Original
111 people have browsed it

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();
});
Copy after login

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');
Copy after login

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');
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!