Home  >  Article  >  Web Front-end  >  How to Replace jQuery Class Toggling with Pure JavaScript?

How to Replace jQuery Class Toggling with Pure JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-21 11:13:291008browse

How to Replace jQuery Class Toggling with Pure JavaScript?

Pure JavaScript Alternative for jQuery Class Toggling

Problem:
Converting a jQuery code that toggles class names for a responsive menu to pure JavaScript.

Solution:

Option 1:

  • Utilize the classList.toggle() method, which is supported by most modern browsers.
<code class="javascript">var menu = document.querySelector('.menu');
menu.classList.toggle('hidden-phone');</code>

Option 2 (Older Browsers):

  • Employ the classList.js library to enable the classList.toggle() functionality.
<code class="javascript">// Install classList.js using your preferred package manager.
var menu = document.querySelector('.menu');
menu.classList.toggle('hidden-phone');</code>

Additional Note:

  • It is recommended to use classes instead of IDs for better encapsulation and to avoid polluting the global namespace.

The above is the detailed content of How to Replace jQuery Class Toggling 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