0

I've multiple elements that all have the same ID (player-left). Can I use JS "this" to only do something to whichever div is being clicked and not the others?

This obviously doesn't work but just for questions sake...

player_left.onclick = function() {
    this.player_left.classList.add("active");   
}
  • 4
    You should not have multiple elements with the same ID, as ID is the [attribute that is used to specify a unique id for an HTML element.](https://www.w3schools.com/html/html_id.asp) – Jay Nyxed Jun 17 '21 at 23:04
  • 2
    Aside from what Jay said, your code isn't working because `this` is the element that was clicked. Try `this.classList.add("active")` – Charlie Bamford Jun 17 '21 at 23:07

1 Answers1

0

Replace use of id attributes

Using the same id attribute value on multiple elements is not valid.

Try looking into element.querySelector and or element.querySelectorAll methods to find elements matching a CSS selector string (See MDN Web Docs for method details). Then change the id attribute of elements (plural) with the same id to use a unique class name or data attribute to identify player elements.

Event Delegation or multiple event handlers

Where to add click handlers depends on whether you use event delegation or assign multiple click handlers to multiple elements. In general

  • the this value inside a click handler (added to an element in JavaScript) is the element to which the handler was added. Handlers are passed an Event object (covered on MDN) as their first argument.

  • The event object's currentTarget property is set to the element to which the event listener was added, and

  • The target property of the event object is set to the element on which the click event was fired. If the player object has child elements, the target object may be a child element that was clicked.

traktor
  • 17,588
  • 4
  • 32
  • 53