Home  >  Article  >  Web Front-end  >  How to Toggle an Element\'s Class without jQuery in Pure JavaScript?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-21 11:11:29782browse

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

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!

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