Q:

How to resolve - some buttons on click Not toggling class

Have 2 buttons with different IDs. When clicked on either, a class should be toggled on the desired selectors. Problem - Only a single button ID works as expected.
document.querySelector("#abc,#xyz").addEventListener("click", function() {
  var e = document.querySelectorAll(".dog,.cat, #abc, #xyz");
  for (var i = 0; i < e.length; i++) {
    e[i].classList.toggle("red");
  }
});

Expect to see - when click on button#abc or button#xyz, class red should be applied to .dog,.cat, #abc, #xyz

A:

The querySelector method returns only the first matched element, use querySelectorAll instead when fetching the buttons

/** use querySelectorAll to get all the elements not only the first matched one **/
/** use forEach method to loop through the returned NodeList object **/

document.querySelectorAll("#abc, #xyz").forEach(btn => {
  btn.addEventListener("click", () => {
    const e = document.querySelectorAll(".dog,.cat, #abc, #xyz");
    e.forEach(el => {
      el.classList.toggle("red");
    });
  });
})
.red {
  background-color: #f00;
}
<button id="abc">abc</button>
<button id="xyz">xyz</button>
<div class="dog">dog</div>
<div class="cat">cat</div>

