javascriptaddeventlistenergetelementbyidids

Apply eventlistener to multiple elements based on their IDs


I have two buttons defined with their IDs : but-toggle, but-close for show hide a panel :

<button id="but-toggle">Panel</button>
<div id="main-panel" style="display:none">
   <button id="but-close">X</button>
   <!-- some panel data -->
</div>

Now i have a JS function which toggle the panel (show/hide) assigned to but-toggle as following :

(function(){document.getElementById("but-toggle").addEventListener("click",function(){
var pan = document.getElementById("main-panel");
if(pan.style.display==="inline-block")
{pan.style.display="none"}
else
{pan.style.display="inline-block"}
});})();

My question is how to use the same function for both buttons without writing two func, one for each. I want a solution for elements based on their ids, since the classes are differents and can't use getElementByClass for this

Thanks


Solution

  • You can use document.querySelector to get a list of elements from a list of IDs:

    function toggleFn() {
      const pan = document.getElementById("main-panel");
      if(pan.style.display === "inline-block") {
        pan.style.display = "none";
      } else {
        pan.style.display = "inline-block";
      }
    }
    document.querySelector("#Id1, #Id2")
      .forEach(elem => elem.addEventListener(toggleFn);