UNPKG

@augment-vir/web

Version:

A collection of augments, helpers types, functions, and classes only for web (frontend) JavaScript environments.

28 lines (27 loc) 1.03 kB
/** * Extract the event target element from an Event. * * @category Web : Elements * @category Package : @augment-vir/web * @example * * ```ts * element.addEventListener('click', (event) => { * const eventTarget = extractEventTarget(event, HTMLButtonElement); * }); * ``` * * @package [`@augment-vir/web`](https://www.npmjs.com/package/@augment-vir/web) */ export function extractEventTarget(event, expectedTargetClass, options = {}) { const target = options.useOriginalTarget ? event.target : event.currentTarget; if (!(target instanceof expectedTargetClass)) { const expectedName = expectedTargetClass.name; const actualName = target?.constructor.name; const message = options.useOriginalTarget ? `Current target from event '${event.type}' was not of type '${expectedName}'. Got '${actualName}'.` : `Target from event '${event.type}' was not of type '${expectedName}'. Got '${actualName}'.`; throw new Error(message); } return target; }