简体   繁体   中英

How to swap between font awesome icons on the click of a button using plain JS?

I created a font-awesome-bars icon button and upon being clicked will show a menu. Apart from that, I also want the font-awesome-bars icon to be replaced by a cross icon. I tried to use toggle but it doesn't work, with the console saying there shouldn't be space characters. But if I remove space characters, the document will not be able to read font awesome icons. Please, help me in this. Thanks you in advance.

<div class="hamburger-menu">
      <i class="fa-solid fa-bars"></i>
    </div>

const hamburgerMenuBtnContainer = document.querySelector('.hamburger-menu');
const hamburgerMenuBtn = document.querySelector('.hamburger-menu i');

hamburgerMenuBtnContainer.addEventListener('click', function(){
   hamburgerMenuBtn.classList.toggle('fa-solid fa-xmark');
});

 const hamburgerMenuBtnContainer = document.querySelector('.hamburger-menu'); const hamburgerMenuBtn = document.querySelector('.hamburger-menu i'); hamburgerMenuBtnContainer.addEventListener('click', function() { hamburgerMenuBtn.classList.toggle('fa-xmark'); hamburgerMenuBtn.classList.toggle('fa-bars'); });
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"> <div class="hamburger-menu"> <i class="fa-solid fa-bars"></i> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM