Home >Web Front-end >JS Tutorial >How to Toggle Classes Using Pure JavaScript and Convert jQuery Code to Vanilla JS?
jQuery has been a popular JavaScript library for simplifying common tasks, including manipulating DOM elements. However, using pure JavaScript offers greater control and flexibility. This article aims to convert the provided jQuery code to pure JavaScript, enabling the toggling of element classes.
<code class="javascript">$('.btn-navbar').click(function() { $('.container-fluid:first').toggleClass('menu-hidden'); $('#menu').toggleClass('hidden-phone'); if (typeof masonryGallery != 'undefined') masonryGallery(); });</code>
The primary requirement is to toggle the menu-hidden and hidden-phone classes for the respective elements. This can be achieved using the classList.toggle() method.
<code class="javascript">const btnNavbar = document.querySelector('.btn-navbar'); // Update selector to query by class const menu = document.querySelector('.menu'); // Update selector to query by class const containerFluid = document.querySelector('.container-fluid'); btnNavbar.addEventListener('click', () => { containerFluid.classList.toggle('menu-hidden'); menu.classList.toggle('hidden-phone'); if (typeof masonryGallery != 'undefined') masonryGallery(); });</code>
classList.toggle() is a standard feature supported by modern browsers. For older browsers, consider using classList.js, a polyfill that provides compatibility.
The above is the detailed content of How to Toggle Classes Using Pure JavaScript and Convert jQuery Code to Vanilla JS?. For more information, please follow other related articles on the PHP Chinese website!