lit / lit-element

LEGACY REPO. This repository is for maintenance of the legacy LitElement library. The LitElement base class is now part of the Lit library, which is developed in the lit monorepo.
https://lit-element.polymer-project.org
BSD 3-Clause "New" or "Revised" License
4.49k stars 318 forks source link

How do you get the actual click event target? #1216

Closed treeder closed 2 years ago

treeder commented 2 years ago

If I have this in my component called my-component

<div @click="${this.doSomething}">click me</div>

And this function:

 doSomething(e) {
        console.log("doSomething", e)
    }

e.target is the web component, ie: my-component, not the div that I would expect. How do I find the div that was clicked?

sorvell commented 2 years ago

The target is the div in this case. Only if an event crosses a shadowRoot target is it retargeted. In that case, event.composedPath() provides an array, the first element of which is the original target.

treeder commented 2 years ago

But it's not the div, that's the problem.

abraham commented 2 years ago

If you just look at the logged output in DevTools it might not show what you're expecting after the fact. You can see that target is the div in the click handler though.

demo

treeder commented 2 years ago

Ahh, interesting. Ya, was looking at dev tools and it shows the target as the component:

image

Good to know though, thanks.