Cannot get attribute value using event.target

Using Rails 5 with Turbolinks and within a loop, I get the element id with a user click its button:

<% foos.each do |foo| %>
  <# Plain HTML for example %>
  <a id="<= foo.id %>" data-action="my-controller#fooMe">Click</a>
<% end %>

I have omitted the controller setup. Inside my Stimulus Controller js:

[...]

fooMe(e) {
  const id = e.target.getAttribute('id')
 console.log(id) // sometimes null
}

Clicking the button I sometimes get the id and other times it’s null. Why? Removing ‘data-turbolinks-track’: ‘reload’ seems to do the trick. How to solve this? How to get the ID using click event? Can I send the attribute’s value on click? Bind?

You probably want to use event.currentTarget instead of event.target. From the event.currentTarget documentation on MDN:

It always refers to the element to which the event handler has been attached, as opposed to event.target which identifies the element on which the event occurred.

Consider what happens when you have a child element in your link, such as:

<a data-action="expandable#expand">
  <span>Expand</span>
</a>

In this case, if you click the word “Expand,” event.target will be the <span>, because that’s where the event occurred. By contrast, event.currentTarget will be the <a> element, since that’s where the event handler is installed.

I don’t think data-turbolinks-track has anything to do with the problem you’re seeing.

4 Likes

Thank you ever so much!