Convert web_sys::Element to web_sys::HtmlInputElement

I saw the convenience Seed function to_input which converts an event target to a web_sys::HtmlInputElement. How do I convert a web_sys::Element to a web_sys::HtmlInputElement?

In particular, I’d like to get the value of an input element with seed::document().get_element_by_id("my_input_el"). I end up with a web_sys::Element, but don’t know how to get the value out of it.

I’ve done a bigger VirtualDOM refactor in this PR and one of the new features are element references.
Excerpt from PR’s description:

Added el_ref + ElRef - users can use native DOM elements safely because ElReg::get checks if the referenced element exists, is in the DOM now and has the right type. And users don’t have to use any error-prone selectors. See examples ( canvas , user_media or todomvc ).

So I recommend to switch to master (Seed 0.6.0 will be released soon so you’ll be prepared) and use those el. references instead of selectors. It’s also easy to choose the element type or cast it into another with ElRefs.
Seed’s changelog for the next version contains some breaking changes but I hope that the migration won’t be painful.


Also there is a helper for getting values from elements - get_value. And as you can see, it’s very cumbersome and dangerous to try get value from inputs.


However to answer the original question:

use wasm_bindgen::JsCast;

// https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/trait.JsCast.html#method.dyn_into
let my_input_as_InputElement = my_input_as_Element.dyn_into::<HtmlInputElement>().ok();

// Or you can use .dyn_ref if you don't want to consume the original element.
1 Like

I was able to read my form inputs from within the update function using the JsCast you posted, thank you. Excited for 0.6.0!