Get element from web_sys EventTarget

I am using Yew, but that shouldn't really matter here

I need to measure the size/location of an HTML element and I can't figure out how to upcast an EventTarget into an HtmlElement. I have tried both into and try_into:

move |e: web_sys::MouseEvent| {
    let elem: web_sys::HtmlElement = e.target().unwrap().try_into().unwrap();
    Msg::SetTab(pos, (0, 0))
}

I have tried treating it like an HtmlElement:

move |e: web_sys::MouseEvent| {
    let width = e.target().unwrap().client_width();
    Msg::SetTab(pos, (0, 0))
}

How do I go about getting the HtmlElement, and more importantly, how would I have figured that out from the docs (I have poured over EventTarget, Node and HtmlElement)?

Hey, I was having trouble as well and the docs did not seem clear. Here's what I had to do.

let form = event.target().unwrap().dyn_ref::<HtmlFormElement>().unwrap().clone();

This also didn't work (the dyn_ref part) until I had to bring
use wasm_bindgen::{JsCast};
into scope
and you might also need to enable all the features (if you haven't already)

web-sys = { version = "0.3.44", features = ["Event", "EventTarget", "HtmlFormElement"] }

based off something I saw here https://github.com/rustwasm/gloo/issues/72

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.