How can i make my code above change the span text without removing the 'i' tag?
function toggle(e) {
let txt = e.innerText;
e.innerText = txt == 'Modo escuro' ? 'Modo claro' : 'Modo escuro';
}
<a onclick="toggle(this)" id="theme-toggle" href="#" >
<i class='bx bx-bulb nav__icon' ></i>
<span >Modo escuro</span>
</a>
live demo here: https://pauletatv.netlify.app
CodePudding user response:
Includes it
Just add your tags into your .innerHTML
element.
let modo = 0;
function toggle(e) {
if (modo == 0) {
e.innerHTML = "<i class='bx bx-bulb nav__icon' ></i><span class='nav__name'>Modo claro</span>";
modo = 1;
} else {
e.innerHTML = "<i class='bx bx-bulb nav__icon' ></i><span class='nav__name'>Modo escuro</span>";
modo = 0;
}
}
<a onclick="toggle(this)" id="theme-toggle" href="#" >Click</a>
In alternative
You can check user theme preference cookies, in this way:
let modo = 0;
if (document.cookie.indexOf("theme=1") !== -1) {
modo = 1;
}
function toggle(e) {
if (modo == 0) {
e.innerHTML = "<i class='bx bx-bulb nav__icon' ></i><span class='nav__name'>Modo claro</span>";
modo = 1;
} else {
e.innerHTML = "<i class='bx bx-bulb nav__icon' ></i><span class='nav__name'>Modo escuro</span>";
modo = 0;
}
}
<a onclick="toggle(this)" id="theme-toggle" href="#" >Click</a>