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.
The provided jQuery code uses the toggleClass() method to toggle the menu-hidden and hidden-phone classes on specified elements.
JavaScript Equivalents:
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>
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>
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!