skip to Main Content

I have this line of code in javascript to select multiple classes to toggle dark mode theme:

let header = document.querySelector('header'),
    mobile = document.querySelector('.mobile'),
    themeButton = document.querySelector('.theme'),
    navbar = document.querySelector('.navbar'),
    videoContainer = document.querySelector('.video-container'),

themeButton.addEventListener('click', () => {
  header.classList.toggle('dark-mode');
  mobile.classList.toggle('dark-mode');
  navbar.classList.toggle('dark-mode');
  videoContainer.classList.toggle('dark-mode');
});

can I simplifiy it so it doesnt take too long? This is my github links if you’re interested: text

2

Answers


  1. You can try iterating over the elements and toggle the dark-mode class for each:

    let elementsToToggle = document.querySelectorAll('header, .mobile, .theme, .navbar, .video-container');
    
    document.querySelector('.theme').addEventListener('click', () => {
      elementsToToggle.forEach(element => {
        element.classList.toggle('dark-mode');
      });
    });
    
    Login or Signup to reply.
  2. I think the best solution should be you need to add the dark-mode to the parent element.

    https://dev.to/phuchieu/dark-theme-with-css-variable-1fjo

    Here is the useful URL you can learn from.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search