Change class and item id when receiving click event with pure javascript

0

I have the following line:

<li id="fecharMenu">
    <i class="mdi mdi-window-close mdi-24px" id="iconFecharMenu"></i>
    <a href="#"></a>
</li>

When the user clicks on <li id="fecharMenu"> , the menu closes and I would like to change the icon and consequently, the id of <li> of <i> , thus:

<li id="abrirMenu">
    <i class="mdi mdi-menu mdi-24px" id="iconAbrirMenu"></i>
    <a href="#"></a>
</li>

JavaScript that I currently have, it "closes" the menu only, I would like to change the icon and id of the li and the icon too, so you can create an event by clicking on the open menu button:

document.getElementById("fecharMenu").addEventListener("click", fecharMenu);
function fecharMenu() {
    document.getElementById("barraLateral").style.width = "60px";
}

How could I only do with JavaScript, without using Jquery?

    
asked by anonymous 09.02.2018 / 12:38

2 answers

1

You can change the attributes as follows:

document.querySelector("#fecharMenu").addEventListener("click", function(){
   this.id = "abrirMenu"; // troca o id da <li>
   var i = this.children[0]; // seleciona o <i>
   i.id = "iconAbrirMenu"; // troca o id do <i>
   i.className = i.className.replace("mdi-window-close","mdi-menu"); // substitui a classe do <i>
});
    
09.02.2018 / 13:39
0

You can use the setAttribute method to change the Id, as follows:

document.getElementById("fecharMenu").setAttribute("id", "abrirMenu");

In this case, I'm assuming you have a css rule for each menu id:

#fecharMenu {
    background-image : (...)
}
#abrirMenu{
    background-image : (...)
}

In this way, when you modify the id, you will change the icon automatically.

But, I believe that manipulating the Id this way is not best practice . I believe that manipulating classes is more appropriate, as follows:

HTML:

<li id="menu" class="aberto">
    <i class="mdi mdi-window-close mdi-24px" id="iconFecharMenu"></i>
    <a href="#"></a>
</li>

JS:

document.getElementById("menu").addEventListener("click", aoClicarMenu);
function aoClicarMenu(event) {
    if (event.target.classList.contains('aberto'){
        event.target.classList.remove('aberto');
        event.target.classList.add('fechado');
    } else {
        event.target.classList.remove('fechado');
        event.target.classList.add('aberto');
    }
    document.getElementById("barraLateral").style.width = "60px";
}

The above code checks whether the DOM element that triggered the event, in this case li , contains the 'open' class, if so, it is removed, and the 'closed' class is added, and vice versa. This way you will be able to toggle the behavior of the element with each click that it receives. For this, you would have to have a CSS to set the menu icon open, or closed:

.aberto {
    background-image : (...)
}
.fechado {
    background-image : (...)
}
    
09.02.2018 / 13:11