Home > Net >  summarize a function that selects multiple elements
summarize a function that selects multiple elements

Time:07-17

I made a function that changed the colors of my site when I clicked (a light-mode-theme), and with that, I had to select the elements that would have their colors changed, one by one, which left the code huge. how could i summarize this selection?

    let h = document.querySelector('header');
    h.classList.toggle('bright-mode');
    let b = document.querySelector('body');
    b.classList.toggle('bright-mode');
    let h1 = document.querySelector('h1');
    h1.classList.toggle('bright-mode');
    let h2 = document.querySelector('h2');
    h2.classList.toggle('bright-mode');
    let h3 = document.querySelector('h3');
    h3.classList.toggle('bright-mode');
    let h4 = document.querySelector('h4');
    h4.classList.toggle('bright-mode');
    let si = document.querySelector('.section-inicio');
    si.classList.toggle('bright-mode');
    let ss = document.querySelector('.section-sobre');
    ss.classList.toggle('bright-mode');
    let sl = document.querySelector('.section-linguagens');
    sl.classList.toggle('bright-mode');
}

CodePudding user response:

Why not just select them all at once with querySelectorAll and then just loop through them and toggle the class?

document.querySelectorAll('header, body, h1, h2, h3, h4, .section-inicio, .section-sobre, .section-linguagens').forEach( el => el.classList.toggle('bright-mode') )

just 1 line of code ;)

CodePudding user response:

You should add the bright-mode class only to the <body> tag. Prior to that in your CSS define all the selectors and their bright colors under that parent selector.

var darkMode = false

function handle_dark_click() {
  if (darkMode == true) {
    disable_dark();
  } else {
    enable_dark();
  }
  darkMode = !darkMode;
}

function enable_dark() {
  document.body.classList.add("bright-mode");
}

function disable_dark() {
  document.body.classList.remove("bright-mode");
}

document.getElementById('toggle-theme').addEventListener('click', handle_dark_click)
/* default is dark */

body {
  background: #333;
}

h1 {
  color: white;
}

div {
  border: 1px solid white;
}


/* all of these are bright mode */

body.bright-mode {
  background: white;
}

body.bright-mode h1 {
  color: black;
}

body.bright-mode div {
  border-color: black;
}
<body>

  <div>
    <h1>hello world</h1>
  </div>

  <button id="toggle-theme">toggle theme</button>

</body>

  • Related