I'm encountering some behavior in LWC that runs counter to my understanding of Event.target -- namely, that it is supposed to represent the DOM element that originally dispatched the event.
Here is an example where a grandchild component dispatches the event and the parent component receives it. event.target
is reflecting the child component, not the grandchild.
parent.html
<template>
<div onmyevent={handleMyEvent}>
<c-child></c-child>
</div>
</template>
parent.js
import { LightningElement } from 'lwc';
export default class Parent extends LightningElement {
handleMyEvent(event) {
console.log(event.target.tagName); // Receiving "C-CHILD" (expecting "C-GRANDCHILD")
}
}
child.html
<template>
<c-grandchild></c-grandchild>
</template>
grandchild.html
<template>
<button onclick={handleButtonClick}>Dispatch event</button>
</template>
grandchild.js
import { LightningElement } from "lwc";
export default class Grandchild extends LightningElement {
handleButtonClick() {
this.dispatchEvent(new CustomEvent("myevent", { bubbles: true, composed: true }));
}
}
Here is a demo: https://stackblitz.com/edit/salesforce-lwc-ezdzna?file=src%2Fmodules%2Fx%2Fapp%2Fapp.html
I would like the parent component to perform an action on the grandchild component when the event is received. How can this be accomplished?