1

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

1 Answers1

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')
    }
  })
})
guest271314
  • 1
  • 15
  • 104
  • 177
  • Should I still be using this in HTML since I have been using other in HTML? – Burak Sümer Feb 23 '19 at 17:34
  • @BurakSümer Is there a need to use global attribute event handler? Whether to use global attribute event handler or not in HTML is a matter of opinion. That is your own decision. See [When did using global event handler attributes within html become “considered bad practice”? \[duplicate\]](https://stackoverflow.com/questions/36388227/) – guest271314 Feb 23 '19 at 17:36
  • With this code I'm having an issue called " ',' expected. ts(1005)" on const. I have researched and updated TS. What might be causing the problem? – Burak Sümer Feb 23 '19 at 17:55
  • Found the problem, there was a ) missing before the const. This code seems like working for me. Thank you. – Burak Sümer Feb 23 '19 at 17:59