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

How to Toggle an Element\'s Class without jQuery in Pure JavaScript?

Susan Sarandon
Release: 2024-10-21 11:11:29
Original
780 people have browsed it

How to Toggle an Element's Class without jQuery in Pure JavaScript?

Toggling Element Classes in Pure JavaScript

Q: How to toggle an element's class in pure JavaScript without jQuery?

jQuery's toggleClass method provides an easy way to toggle the classes of an element. But how can this be achieved using pure JavaScript?

A:

  1. document.classList.toggle():

    Modern browsers support the classList.toggle method, which simplifies class manipulation. For example:

    <code class="js">var menu = document.querySelector('.container-fluid');
    menu.classList.toggle('menu-hidden');</code>
    Copy after login
  2. classList.js:

    For older browsers that lack classList.toggle, you can use the classList.js polyfill:

    <code class="js">var menu = document.querySelector('.menu');
    classList.toggle(menu, 'hidden-phone');</code>
    Copy after login

Additional Notes:

  • Class List: Use class names instead of IDs for improved efficiency.
  • Avoid IDs: IDs create global variables in the JavaScript window object.

The above is the detailed content of How to Toggle an Element\'s Class without jQuery in 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!