What logic can I use to remove a class and add the same removed class to another element?

Asked

Viewed 56 times

0

I would like to be able to click the buttons on the menu to add the stylized class and return to the normal style on the previous button for example: when I click on the button 1 it is styled, then when I click on the button 2 it is styled and the button 1 loses the style.

inserir a descrição da imagem aqui

The current code is as follows::

 let menu = document.querySelectorAll('.menu-item');
 menu.forEach((item) =>{

    item.addEventListener('click', function(){   
       item.classList.add('menu-item-actived');   
       
       
    });

 });
  • item.addeventlistener('click', Function(el)' item.classList.remove('menu-item-actived'); el.classList.add('menu-item-actived') }); Try this

  • the easiest way would be to remove the style of all buttons and then add only to the button that should have the style

  • Hello Ricardo all right? Could you tell me more about how to do this?

  • hugocsl Thanks for the tip, I’ll try!

1 answer

1


Blza Filipe? I don’t know if it’s been solved but I’ll leave a simple solution here:

Whenever a button is clicked, it will be checked if there is a button with the "menu-item-actived" class, and the class will always be removed before adding on another button.

let menu = document.querySelectorAll('.menu-item')

menu.forEach((item) => {

  item.addEventListener('click', function() {

    let botao = document.querySelectorAll('#minha-div .menu-item-actived');

    botao.length != 0 ? botao[0].classList.remove("menu-item-actived") : botao.length;

    item.classList.add('menu-item-actived');

  });

});
.menu-item-actived {
  background-color: #ff0000;
  color: #fff;
}
<div id="minha-div">
  <input type="button" class="menu-item" value="Botão 1">
  <input type="button" class="menu-item" value="Botão 2">
  <input type="button" class="menu-item" value="Botão 3">
  <input type="button" class="menu-item" value="Botão 4">
</div>

  • Hello Igor, thank you so much for your reply! I had solved otherwise (gambiarra), but I will try it your way!

  • @Filipegomes Igor Bezerra’s solution served you?

  • @Cmte Cardinal Yes, it worked!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.