1

I'm trying to add a class to an element after an event listener detects a click of said element, I've used the following code, but it's not specific and any element being clicked will receive the class.

document.addEventListener('click', (event) => {
   event.target.classList.add("selected");
});

what I thought would work was this:

var element = document.getElementById("object1");
document.element.addEventListener('click', (event) => {
   element.classList.add("selected");
});

Is there anything else I can use?

Jaco
  • 11
  • 1

1 Answers1

0

This will work

var element = document.getElementById("object1");
element.addEventListener('click', (event) => {
   element.classList.add("selected");
});
The Onin
  • 5,068
  • 2
  • 38
  • 55
  • Please try to explain **why** this will work as part of the answer, code only answers generally encourage copy-pasting rather than actually learning what went wrong. – DBS Feb 22 '22 at 10:13