kidwit kidwit - 4 months ago 21
Javascript Question

e.target properties returning undefined

I am having trouble trying to access

target
properties in my
onClick
handler.

Here is what I'm trying (using React FYI):

onLinkClick(e){
this.setState({ menuOpen: false });

var link = e.target.href;
console.log(link);//returns undefined

this.doSomeStuff(link); //example
}


However, when I remove the
href
from
e.target
and log it to the console, I get:

<span href="work" data-reactid=".0.0.1.2.$2.0">Work</span>


Any ideas?

Answer

Use .getAttribute('href'). href is a non-standard property of <span> and you really shouldn't do that. Use an <a> instead.

class Test extends React.Component {
  constructor(props) {
    super(props);
    
    this.onLinkClick = this.onLinkClick.bind(this);
  }

  onLinkClick(e) {
    var link = e.target.getAttribute('href');
    alert(link);
  }
  
  render() {
    return (
      <span href="work" onClick={this.onLinkClick}>Work</span>
    );
  }
}

ReactDOM.render(<app><Test /></app>, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Comments