Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
How to change fontawsome icon onclick

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>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You have to separate classes by comma, dont use space

icon.classList.remove('far', 'fa-moon');
icon.classList.add('fas', 'fa-sun', 'fa-lg');
about 4 years ago · Juan Pablo Isaza Report

0

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");
            }
            
        });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!