I tried the below code but is not showing the ‘fa-xmark’ rather it’s showing the ‘fa-bars’.
I want ‘fa-xmark to show when I click on the ‘fa-bars’
const toggleBtn = document.querySelector('.toggle_btn')
const toggleBtnIcon = document.querySelector('.toggle_btn i')
const dropDownMenu = document.querySelector('.dropdown-menu')
toggleBtn.onclick = function() {
dropDownMenu.classList.toggle('open')
const isOpen = dropDownMenu.classList.contains('open')
toggleBtnIcon.classList = isOpen ?
'fa-solid fa-xmark' :
'fa-solid fa-bars'
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<a href="#" class="sign_btn">Signup</a>
<div class="toggle_btn">
<i class="fa-solid fa-bars"></i>
<div class="dropdown-menu">
<li><a href="hero">Home</a></li>
<li><a href="hero">Task</a></li>
<li><a href="hero">File</a></li>
<li><a href="hero">About</a></li>
<li><a href="#" class="sign_btn">Signup</a></li>
</div>
2
Answers
The JS is fine (I would have used IDs instead of classes but it is alright. You just don’t have the right HTML.
The error says that it does not find an object with the class "toggleBtn".
Here, use this HTML:
https://jsfiddle.net/cdntp7kf/1/
You can try this :