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

How to Toggle Classes Using Pure JavaScript and Convert jQuery Code to Vanilla JS?

Susan Sarandon
Release: 2024-10-21 10:50:02
Original
602 people have browsed it

How to Toggle Classes Using Pure JavaScript and Convert jQuery Code to Vanilla JS?

Toggling Classes in Pure JavaScript: Convert jQuery 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.

jQuery Code for Reference

<code class="javascript">$('.btn-navbar').click(function() {
  $('.container-fluid:first').toggleClass('menu-hidden');
  $('#menu').toggleClass('hidden-phone');

  if (typeof masonryGallery != 'undefined') masonryGallery();
});</code>
Copy after login

Pure JavaScript Solution

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>
Copy after login

Browser Compatibility

classList.toggle() is a standard feature supported by modern browsers. For older browsers, consider using classList.js, a polyfill that provides compatibility.

Additional Considerations

  • Avoid using IDs as selectors, as they can leak globals into the JS window object.
  • Use a class-based selector for higher specificity and performance.

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!

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!