I have this code which should change the fontawsome icon onclick but it's not working, I tried it with a picture and it worked but when using font awsome it doesn't. Please help.
<script>
var icon = document.getElementById("icon");
icon.onclick = function(){
document.body.classList.toggle("darkTheme");
if(document.body.classList.contains("darkTheme")){
icon.classList.remove('far fa-moon');
icon.classList.add('fas fa-sun fa-lg');
/*icon.src = "img/sun.png";*/
localStorage.setItem("theme", "dark");
}
else{
icon.classList.remove('fas fa-sun fa-lg');
icon.classList.add('far fa-moon');
/*icon.src = "img/moon.png";*/
localStorage.setItem("theme", "light");
}
}
</script>
You have to separate classes by comma, dont use space
icon.classList.remove('far', 'fa-moon');
icon.classList.add('fas', 'fa-sun', 'fa-lg');
This should work at adding the classes you need to the element. Also it is cleaner to use an event listener to keep JS CSS HTML separated. And as @Ali Yaghoby mentioned you need to separate each class with a comma
const icon = document.getElementById('icon');
icon.addEventListener('click', ()=>{
if(document.body.classList.contains("darkTheme")){
icon.classList.remove('far', 'fa-moon');
icon.classList.add('fas', 'fa-sun', 'fa-lg');
localStorage.setItem("theme", "dark");
}
else{
icon.classList.remove('fas', 'fa-sun', 'fa-lg');
icon.classList.add('far', 'fa-moon')
localStorage.setItem("theme", "light");
}
});