Nilos
Nilos

Reputation: 359

event.target.name is undefined

I am trying to use e.target.name in react to set the state as I have done before, however e.target.name seems to be undefined for some reason and I can't figure out why, if any one has a suggestion it will be welcome. thanks!

<li
    onMouseEnter={this.handleMouseEnter.bind(this)}
    name="HOME"
    id="some id"
    style={main.element}
>
    HOME
</li>    

my event handler has only a debugger for me to play with

handleMouseEnter(e) {
    debugger
}

and when i try to get the value of the name property i get undefined

e.target
//<li name=​"HOME" id=​"some id" style=​"padding:​ 10px;​">​HOME​</li>​
e.target.name
//undefined
e.target.id
//"some id"

Upvotes: 18

Views: 73812

Answers (3)

Shivani Karthik
Shivani Karthik

Reputation: 1

Had the same issue, Tried this and it worked

event.getSource().get("v.name");

Upvotes: 0

Ele
Ele

Reputation: 33736

  • Form fields are the elements who must use the attribute name.
  • The JS engine will automatically set that attribute within the form elements (input, select, etc).

document.querySelector('li').addEventListener('click', function(e) {
  console.log('Directly: ' + e.target.name);// prints null
  console.log('Using getAttribute: ' + e.target.getAttribute('name')); // prints ele
});

document.querySelector('input').addEventListener('click', function(e) {
  console.log('Directly: ' + e.target.name);
  console.log('Using getAttribute: ' + e.target.getAttribute('name')); // prints ele
});
<input name="ele" placeholder="Click me!">
<li name="ele">Click me!</li>


Upvotes: 12

Sync
Sync

Reputation: 3797

name is an attribute and needs function getAttribute(...) to be fetched. As @Ele has pointed out, the suggested solution would be

var name = e.target.getAttribute('name'); //'HOME'

Upvotes: 38

Related Questions