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

How to Toggle Element Classes with Pure JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-10-21 11:20:29389browse

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>
  • 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>

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!

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