1

I have a simple HTML table with ids in some cells:

<td id="x-11"><b>Is it a cell?</b> What a cell!</td>

Now I'd like to pass the ID to a JavaScript function triggered onclick:

const $tds = document.querySelectorAll('td[id]')
    for (let i = 0; i < $tds.length; i++)
        $tds[i].addEventListener('click', ev => console.log(ev.target.id))

It works as expected if I click an empty area or normal text within the cell. But if I hit the text inside the <b> element something strange happens: The browser says that the <b> element is the ev.target - although it has no listener whatsoever.

Can someone explain this behavior or offer a solution?

Update: As stated in the comments, Difference between e.target and e.currentTarget provides the answer (for ActionScript, but that doesn't make a difference here) but the question is different.

wortwart
  • 3,139
  • 27
  • 31
  • 1
    `event` object always targets the element which had **caused** the event, **regardless of the fact** that the element has event listener or not. In your case, `` is inside of the element which has event listener, so it becomes `event.target`. – vrintle Sep 27 '18 at 15:17
  • 3
    Possible duplicate of [Difference between e.target and e.currentTarget](https://stackoverflow.com/questions/5921413/difference-between-e-target-and-e-currenttarget) – Dan O Sep 27 '18 at 15:20
  • change target to currentTarget – gugateider Sep 27 '18 at 15:21
  • Thank you, you're right. Strangely, Web Inspector shows `currentTarget` as `null` in my browser but it works anyway. And the naming of `target`/`currentTarget` suggest it's rather the other way around ... – wortwart Sep 27 '18 at 16:07

1 Answers1

0

You need to use this or ev.currentTarget that always refers to the DOM element the listener was attached to, instead, the ev.target will refer to the element that fired the event, in this case, the DOM element that was clicked :

$tds[i].addEventListener('click', function(){
   console.log(this.id)
});
//Or
$tds[i].addEventListener('click', ev => console.log(ev.currentTarget.id))
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • I like the solution with `this` but it won't work within an arrow function. It's `function(ev) {console.log(this.id)}`. – wortwart Sep 27 '18 at 16:12