Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

165
Visualizações
How can I set a className of a tag from localStorage in javaScript?

my Webpage has dark theme feature and this can be changed by tapping on a button, but I want to keep the status of theme after the page get refreshed by the user. it works like if the body tag has "light" class, the theme is light and when it doesnt have "light" class the theme is dark.

I can set property of className of body in localStorage but the problem is that when I refresh the page the read className from localStorage doesnt get set to body tag.

CSS :

body.light {
  --img-bg: url("../assets/images/bg-desktop-light.jpg");
  --clr-primary: hsl(243, 12%, 30%);
  --clr-page-bg: hsl(0, 0%, 98%);
  --clr-card-bg: hsl(0, 0%, 100%);
  --clr-gb-1: hsl(240, 8%, 24%);
  --clr-gb-2: hsl(243, 12%, 30%);
  --clr-gb-3: hsl(252, 6%, 83%);
  --clr-gb-4: hsl(237, 10%, 64%);
  --clr-gb-5: hsl(252, 9%, 73%);
  --clr-gb-6: hsl(252, 21%, 94%);
}

Js :

  themeSwitcherBtn.addEventListener("click", () => {
    bodyTag.classList.toggle("light");
    const themeArr = [
      {
        bodyClass: bodyTag.className,
      },
    ];
    const themeClass = localStorage.setItem(
      "themeInfo",
      JSON.stringify(themeArr)
    );
  });

    window.onload = () => {
      const themeClass = JSON.parse(localStorage.getItem("themeInfo")) ? bodyTag.classList.add(themeClass[0].bodyClass) : bodyTag.className === "";
    };
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The problem is in the themeClass variable. You're using it before initialization. The themeClass value is the result returned by the ternary operator. So, to make it works here is a suggestion:

window.onload = () => {
  const themeClass = JSON.parse(localStorage.getItem("themeInfo"));
  bodyTag.className = themeClass ?themeClass[0].bodyClass : "";
};
about 4 years ago · Juan Pablo Isaza Relatório

0

try this:

const lsToken = 'hasLightTheme';
const tag = 'light';
themeSwitcherBtn.addEventListener("click", () => {
  localStorage.setItem(lsToken, bodyTag.classList.toggle(tag));
});

window.onload = () => {
  const hasLightTheme = !!localStorage.getItem(lsToken)
  bodyTag.classList.toggle(tag, hasLightTheme);
};

I removed the storing of the theme in an array as I didn't see any use for that? I've also stored the localStorage key and theme name in variables. I've simplified the onload function quite a bit. Also some other simplifications like removed the declaration of variables that were never used for anything

has "light" class, the theme is light and when it doesnt have "light" class the theme is dark.

This is an okay solution if you know you will never have more than a default theme(with no class on body) and custom theme (light in this case)

But if you foresee having more themes in the future this solution isn't great.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda