On a click eventListener with e.target.name, child element with same name attribute is showing as undefined

1 week ago 20
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:

const scissorsEl = document.querySelector(".icon-scissors"); scissorsEl.addEventListener("click", (e) => { state.setUserChoice(e.target.dataset.name); // <-- grab from the "dataset" property console.log("label:", e.target.dataset.name); // <-- and here }); const state = { userChoice: "", setUserChoice(choice) { this.userChoice = choice; }, } <script src="https://kit.fontawesome.com/03a64a1742.js" crossorigin="anonymous"></script> <button class="icon icon-scissors" data-name="scissors"> <i class="fa-solid fa-hand-scissors" data-name="scissors"></i> </button>

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.

David's user avatar

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); });

Sanjib's user avatar

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); });

Pooja Rathod's user avatar

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); });

Unmitigated's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article