Dark/Light Mode Toggle Button Question

I have completed my portfolio website project and wanted to add local storage so the dark/light themes are saved. Everything works expect one small detail. When i set the theme to light and reload the page i have to click the toggle button twice for it to change back to dark theme. When the theme is set to dark body element’s class changes to either “dark” or “light”.
Here is the code:
HTML

<body class="dark">
</body>

After setting it to light:

<body class="light">
</body>

After page reload:

<body class="dark light">
<body>

JavaScript

const body = document.body;
const toggle = document.getElementById("toggle");

const theme = localStorage.getItem("theme");

if (theme) {
  body.classList.add(theme);
}

const toggleButton = () => {
  if (body.classList.contains("dark")) {
    body.classList.replace("dark", "light");
    localStorage.setItem("theme", "light");
  } else {
    body.classList.replace("light", "dark");
    localStorage.setItem("theme", "dark");
  }
};

toggle.onclick = toggleButton;

here you can see that after reload body’s class changed to “dark light”
image

Website Link

How do i make it so after the page reloads body’s class is set to “light” only?

Hi again!

So, if a user saves light mode, leaves, and returns, the DOM “refreshes” to its original state, and dark is placed back onto the body. In this case, you need to click the button twice because of the conditional.

if (body.classList.contains("dark")) {
    body.classList.replace("dark", "light");

The code will check if the body has dark (which it does), replace it with light, and end there. So, now you have to click again for the second conditional to take effect.

Could you make the design inherently dark (without the class) and only save/remove setItem from local storage if light is toggled?

const toggleButton = () => {
  if (body.classList.contains("light")) {
    body.classList.toggle("light");
    localStorage.removeItem("theme");
  } else {
    body.classList.toggle("light");
    localStorage.setItem("theme", "light");
  }
};