October 21, 2024
Chicago 12, Melborne City, USA
javascript

Run function on whichever element was clicked


Let’s say I have multiple buttons which each have a .btn-swatch class. When any of them is clicked, I want to act on the one that was clicked. So far, I can just figure out how to act on a specific element from the array.

const swatchBtn = document.getElementsByClassName('btn-swatch');

swatchBtn.item(1).addEventListener("click", function (e) {
  const swatchColor = e.target.getAttribute('data-color');
  const selectedEl = document.querySelector('[data-selected]');
  selectedEl.classList.add(swatchColor);
});



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video