I want to change the class ‘fa-meh-blank’ to ‘fa-smile-wink’ but it doesn’t work.
When I flip the two classes, however, it works. I don’t understand what’s wrong, what would anyone have an idea?
const icone = document.querySelector("i");
console.log(icone);
//Je soumets
icone.addEventListener('click', function() {
console.log('icône cliqué');
icone.classList.toggle('happy');
icone.classList.toggle('fa-smile-wink');
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<div class="container">
<div class="bloc-central">
<h1>Projet Abonnez-vous</h1>
<div class="bloc-btn">
<i class="far fa-meh-blank"></i>
<button class="btn">Abonnez-vous</button>
</div>
</div>
</div>
3
Answers
I tried the 'fa-meh-blank' Remove. When I clicked it worked. And when I clicked again, my icon disappeared completely.
I managed to find the solution. I think I expressed myself badly. I wanted to alternate the icons with each click. The following javascript works perfectly.
My new JavaScript:
I think the code is working properly now.
You forgot to delete the old class before adding the new one.
Your function is adding classes "happy" and "fa-smile-wink", rather than toggling between the classes which will change the icon. This is what I would do to toggle the icons, using vanilla JavaScript: