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

How to Toggle Element Classes with Pure JavaScript?

Linda Hamilton
Release: 2024-10-21 11:20:29
Original
386 people have browsed it

How to Toggle Element Classes with Pure JavaScript?

Toggling Element Classes with Pure JavaScript: A Comprehensive Guide

Introduction

In JavaScript, controlling element classes is crucial for dynamic web development. One common task is toggling classes to change an element's appearance or functionality. While jQuery has made this task straightforward, it's essential to understand how to accomplish it using pure JavaScript.

jQuery Solution and JavaScript Equivalents

The provided jQuery code uses the toggleClass() method to toggle the menu-hidden and hidden-phone classes on specified elements.

JavaScript Equivalents:

  • Option 1 (classList.toggle):

Modern browsers support the classList.toggle() method. For example:

<code class="javascript">var menu = document.querySelector('.menu'); // Using a class instead, see note below.
menu.classList.toggle('hidden-phone');</code>
Copy after login
  • Option 2 (classList.js for Legacy Browsers):

Older browsers can use the classlist.js library to implement classList.toggle(). Example:

<code class="javascript">var classList = require('classlist'); // Import the library
var menu = document.querySelector('.menu');
classList.toggle(menu, 'hidden-phone');</code>
Copy after login

Clarification on ID Usage

As a side note, it's recommended to avoid using IDs in your JavaScript code. IDs are globals that leak into the JavaScript window object, which can lead to unexpected behavior and potential memory leaks. Instead, use classes for more modular and encapsulated code.

The above is the detailed content of How to Toggle Element Classes with 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!