ARTICLE AD BOX
The name attribute is not a global attribute and doesn't apply to all elements.
Instead, consider using data-* attributes. For example:
The idea behind data-* attributes is to store any relevant pieces of information for an element which doesn't necessarily fit into existing standard attributes for that element.
221k43 gold badges252 silver badges342 bronze badges
Use e.currentTarget instead. It always refers to the element the listener is attached to:
const scissorsEl = document.querySelector(".icon-scissors"); scissorsEl.addEventListener("click", (e) => { state.setUserChoice(e.currentTarget.name); console.log(e.currentTarget.name); });2331 silver badge3 bronze badges
The issue is the difference between e.target and e.currentTarget.
e.target is the element that actually triggered the event.
e.currentTarget is the element that the event listener is attached to.
When you click the icon, e.target is the <i> element. Even though you added a name attribute to it, <i> tags do not natively support name, so it returns undefined.
SOLUTION:
scissorsEl.addEventListener("click", (e) => { // This will always refer to the button const choice = e.currentTarget.name; state.setUserChoice(choice); console.log("label:", choice); });New contributor
Pooja Rathod is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
If you use a regular function instead of an arrow function, you can use this to refer to the element that the event listener was attached to.
scissorsEl.addEventListener("click", function(e) { state.setUserChoice(this.name); console.log("label:", this.name); });91.7k12 gold badges106 silver badges109 bronze badges
Explore related questions
See similar questions with these tags.
