Burak Sümer
Burak Sümer

Reputation: 11

How to select two elements at once and make my code affect both of them with querySelector?

I'm adding my website a night mode. And I've done most of the coding part and while started to change some parts about design. I'm going to need to change my hrs in the HTML and add them a solid border to make them visible in the dark mode. Here's my code:

<p class="dark">
  <a id="moon" href="#" onclick="localStorage.setItem('mode', (localStorage.getItem('mode') || 'dark') === 'dark' ? 'light' : 'dark'); 
                localStorage.getItem('mode') === 'dark' ? 
                document.querySelector('body').classList.add('dark') : 
                document.querySelector('body').classList.remove('dark')" title="nm">Night Mode🌓
                </a>
</p>

What I want to do is that add a class to my hrs as well with this code using querySelector but once I added the hrs to the code it only affects body and not the hrs. What can I do to make the code affect both of them.

The code bellow is working but I also found an eaiser way to do what I wanted. To CSS code I simply added this code and it is working nice as well.

body.dark hr {
border: 1px solid #808080;
}

Upvotes: 1

Views: 49

Answers (1)

guest271314
guest271314

Reputation: 1

You can use .querySelectorAll() and .forEach() method of NodeList

document.getElementById("moon").addEventListener("click", e => {
  localStorage.setItem('mode', (localStorage.getItem('mode') || 'dark') === 'dark' ? 'light' : 'dark'
  const elements = document.querySelectorAll("body, hr");
  elements.forEach(el => {
    if (localStorage.getItem('mode') === 'dark') {
      el.classList.add('dark') 
    } else {
      el.classList.remove('dark')
    }
  })
})

Upvotes: 1

Related Questions