0

The following function returns undefined instead of the ID of the element that is clicked on. Why is it doing this?

// get id of the target element that is clicked on
getId: function() {
    var cell = document.getElementById('board');
    cell.addEventListener('click', function(e) {
    return e.target.id;
    });
},
Tiramisu
  • 35
  • 1
  • 9

1 Answers1

2

Your getId()function just add a listener, and don't return the id...

Consider this snippet, it's working:

var cell = document.getElementById('board');
var id = cell.addEventListener('click', function(e) {
  console.log (e.target.id);
});
<body>
  <div id="board">
    <div id="messageArea">Let's begin! Enter a position below. </div>
    <table>
      <tr>
        <td id="00">00</td><td id="01">01</td><td id="02">02</td><td id="03">03</td><td id="04"04>04</td><td id="05">05</td><td id="06">06</td>
      </tr>
      <tr>
        <td id="10">10</td><td id="11">11</td><td id="12">12</td><td id="13">13</td><td id="14">14</td><td id="15">15</td><td id="16">16</td>
      </tr>
      <tr>
        <td id="20">20</td><td id="21">21</td><td id="22">22</td><td id="23">23</td><td id="24">24</td><td id="25">25</td><td id="26">26</td>
      </tr>
      <tr>
        <td id="30">30</td><td id="31">31</td><td id="32">32</td><td id="33">33</td><td id="34">34</td><td id="35">35</td><td id="36">36</td>
      </tr>
      <tr>
        <td id="40">40</td><td id="41">41</td><td id="42">42</td><td id="43">43</td><td id="44">44</td><td id="45">45</td><td id="46">46</td>
      </tr>


    </table>

  </div>

  <form>
    <input type="text" id="guessInput" placeholder="A0">
    <input type="button" id="fireButton" value="Fire!">
  </form>

</body>
Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
  • Yes, I tested it with console.log and saw it was working which was why I was confused. But how would I return e.target.id in the getId() function? If I do that, I get a ReferenceError saying that 'e is not defined' – Tiramisu Aug 24 '16 at 03:38
  • @Anon the question was marked as a duplicate, well, because it was answered in details already. Please bother checking the duplicate. – zerkms Aug 24 '16 at 03:39