Is there a better way to get the target of a event...
# javascript
c
Is there a better way to get the target of a event as a HTMLElement?
Copy code
val iframeDocument = element.contentWindow?.document
iframeDocument?.body?.addEventListener("mouseup", callback = { event ->
    val target = event.target?.unsafeCast<HTMLElement>()!!
})
r
It will probably fail. Not all event targets are elements.
t
Check not
null
only (original)
Copy code
val target = event.target?.unsafeCast<HTMLElement>()!!
Unsafe mode:
Copy code
val target = event.target.unsafeCast<HTMLElement>()
Safe mode:
Copy code
val target = event.target as?HTMLElement
if (target != null) {
    // action
}
c
But there is no option to check the type before casting is there? @Robert Jaros
t
Copy code
val target = event.target
if (target is HTMLElement>) {
    // action
}
c
@turansky That aint working because of the type of event.target is public external abstract class EventTarget