I hope all is well,
I want to change the menu from the hamburger to closed when clicked. I just need to target the name attribute on the icon using ionicons.com
<ion-icon name="menu-sharp" class="text-3xl cursor-pointer"></ion-icon>
I can target the element using:
const menu = document.querySelector('ion-icon');
but when i try to toggle or add/remove using:
menu.addEventListener('click', () => {
console.log('clicked')
toggleMenu()
})
function toggleMenu() {
menu.classList.remove('menu-sharp')
menu.classList.add('close-sharp')
navLinks.classList.toggle('top-[14%]')
}
it doesn't work because i am not targeting the name attribute from the HTML above
Well in case if you want to toggle name attribute this code will not work becouse you targeting class of the element by menu.classList.remove. If you want to change the attribute name you have to target the attribute name like this:
const menu = document.querySelector('ion-icon');
menu.addEventListener('click', () => {
toggleMenu();
})
function toggleMenu() {
menuAttr = menu.getAttribute('name');
if(menuAttr == 'menu-sharp'){
menu.setAttribute('name','close-sharp');
}else{
menu.setAttribute('name','menu-sharp');
}
Hope this help you!