0

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

4
  • classList is used to manage the classes of an element. To mutate other attributes either set them directly if available or use setAttribute. menu.setAttribute('name', 'close-sharp') Commented Mar 19, 2023 at 12:12
  • Does this answer your question? Change HTML name attribute using JavaScript Commented Mar 19, 2023 at 12:27
  • First of all "navLinks" varible is not defined. Second, you have to use ";" at the end of every expression. Commented Mar 19, 2023 at 12:33
  • @luknij semicolons aren't required here. And it seems a safe assumption that navLinks is defined elsewhere given that the question is about mutating the name attribute of the menu element. Commented Mar 19, 2023 at 13:04

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.