Event delegation is a simple, but powerful leveraging of the DOM event system which allows for easier adding of functionality to dynamically created content; as well as being an interesting performance optimization.
At 3.00 why check "event.target instanceof Element && event.target.tagName === 'BUTTON'" and not only the second condition ?
At 3'43 the same question for "event.target instanceof Element && event.target.closest('button')" -)
Hi antonin,
This is me just being extremely safe with my types.
The event.target
property is of type EventTarget
, and not Element
. So I am doing the instanceof Element
check so that I can safely use the Element.tagName
property and Element.closest
function. The event.target
property could be anything that implements the EventTarget
interface.
The code in my example would still run totally fine without the instanceof
checks. If you are working with TypeScript then you will need to narrow the EventTarget
type down to Element
before it will let you use any Element
functionality