Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 328
Nilos Avatar asked Feb 26 '18 14:02

Nilos


2 Answers

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'
like image 113
Sync Avatar answered Sep 21 '22 17:09

Sync


  • 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>

like image 21
Ele Avatar answered Sep 22 '22 17:09

Ele