Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda