{"record":{"id":"022f3ed3a55ce167","repo":"yewstack/yew","slug":"i-m-sure-this-event-has-a-target","errorCode":null,"errorMessage":"I'm sure this event has a target!","messagePattern":"I'm sure this event has a target!","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"warning","filePath":"website/versioned_docs/version-0.21/concepts/basic-web-technologies/wasm-bindgen.mdx","lineNumber":147,"sourceCode":"`JsCast` provides both checked and unchecked methods of casting - so if at runtime if you are\nunsure what type a certain object is, you can try to cast it, which returns possible failure types like\n[`Option`](https://doc.rust-lang.org/std/option/enum.Option.html) and\n[`Result`](https://doc.rust-lang.org/std/result/enum.Result.html).\n\nA common example of this in [`web-sys`](./web-sys.mdx) is when you are trying to get the\ntarget of an event. You might know what the target element is, but the\n[`web_sys::Event`](https://wasm-bindgen.github.io/wasm-bindgen/api/web_sys/struct.Event.html) API will always return an [`Option<web_sys::EventTarget>`](https://wasm-bindgen.github.io/wasm-bindgen/api/web_sys/struct.Event.html#method.target).\nYou will need to cast it to the element type so you can call its methods.\n\n```rust\n// need to import the trait.\nuse wasm_bindgen::JsCast;\nuse web_sys::{Event, EventTarget, HtmlInputElement, HtmlSelectElement};\n\nfn handle_event(event: Event) {\n    let target: EventTarget = event\n        .target()\n        .expect(\"I'm sure this event has a target!\");\n\n    // maybe the target is a select element?\n    if let Some(select_element) = target.dyn_ref::<HtmlSelectElement>() {\n        // do something amazing here\n        return;\n    }\n\n    // if it wasn't a select element then I KNOW it's a input element!\n    let input_element: HtmlInputElement = target.unchecked_into();\n}\n```\n\nThe [`dyn_ref`](https://wasm-bindgen.github.io/wasm-bindgen/api/wasm_bindgen/trait.JsCast.html#method.dyn_ref)\nmethod is a checked cast that returns an `Option<&T>`, which means the original type\ncan be used again if the cast failed and thus returned `None`. The\n[`dyn_into`](https://wasm-bindgen.github.io/wasm-bindgen/api/wasm_bindgen/trait.JsCast.html#method.dyn_into)\nmethod will consume `self`, as per convention for `into` methods in Rust, and the type returned is\n`Result<T, Self>`. If the casting fails, the original `Self` value is returned in `Err`. You can try again","sourceCodeStart":129,"sourceCodeEnd":165,"githubUrl":"https://github.com/yewstack/yew/blob/0e4a05472fac4e5fce1befe60fa4a1e43a36b6a3/website/versioned_docs/version-0.21/concepts/basic-web-technologies/wasm-bindgen.mdx#L129-L165","documentation":"This docs example calls event.target() and expects a value. Event.target() returns Option: it is None for events that were never dispatched, synthetic events created and fired manually without a target, and some framework-generated events. When that happens the expect panics - the snippet is only safe for genuine browser-dispatched DOM events.","triggerScenarios":"Using the copied handler for programmatically created events (Event::new(\"custom\") inspected before/without a real dispatch); test utilities dispatching bare events; handlers for event types whose target can legitimately be null.","commonSituations":"Reusing the doc handler for custom application events dispatched via dispatchEvent; event objects inspected outside handlers; testing harnesses that construct Event values directly.","solutions":["Prefer current_target() when you want the element the listener is attached to - it is always set during dispatch","Handle the Option: if let Some(target) = event.target() { ... }","When dispatching synthetic events, dispatch them on a real node so the target is populated","Use dyn_ref instead of dyn_into for downstream casts so mismatches degrade gracefully instead of panicking"],"exampleFix":"// before\nlet target: EventTarget = event.target().expect(\"I'm sure this event has a target!\");\n\n// after\nif let Some(target) = event.target() {\n    // inspect target...\n}\n// or, when you actually want the element the listener is bound to:\nif let Some(current) = event.current_target() {\n    // ...\n}","handlingStrategy":"type-guard","validationCode":null,"typeGuard":"fn target_as_element(event: &web_sys::Event) -> Option<web_sys::Element> {\n    event.target().and_then(|t| t.dyn_into::<web_sys::Element>().ok())\n}","tryCatchPattern":null,"preventionTips":["Prefer current_target() when the listener's own element is what you want","Never expect() on event.target(); handle the Option","Dispatch synthetic events from a real node so the target is populated"],"tags":["events","docs","web-sys","optional-target"],"backgroundTag":"event-target-missing","analyzedSha":"0e4a05472fac4e5fce1befe60fa4a1e43a36b6a3","analyzedAt":"2026-08-22T21:16:31.212Z","schemaVersion":2},"datasetVersion":"2026-08-23T01:17:44.959Z"}