WASM/RUST/DOM compile failed

I try to compile this code (I am new to Rust and WASM) with this:

wasm-pack build --target web
[INFO]: :dart: Checking for the Wasm target...
[INFO]: :cyclone: Compiling to Wasm...
Compiling hello-wasm v0.1.0 (/Users/laplante/rust/hello-wasm)
error[E0599]: no method named set_text_content found for enum Result in the current scope
--> src/lib.rs:18:9
18 | val.set_text_content(Some("Hello from Rust!"));
| ^^^^^^^^^^^^^^^^ method not found in Result<Element, JsValue>

error[E0308]: mismatched types
--> src/lib.rs:20:23
20 | body.append_child(&val);
| ^^^^ expected struct Node, found enum Result
= note: expected reference &Node
found reference &Result<Element, JsValue>

Some errors have detailed explanations: E0308, E0599.
For more information about an error, try rustc --explain E0308.
error: could not compile hello-wasm due to 2 previous errors
Error: Compiling your crate to WebAssembly failed
Caused by: failed to execute cargo build: exited with exit status: 101
full command: "cargo" "build" "--lib" "--release" "--target" "wasm32-unknown-unknown"

The code is:

use wasm_bindgen::prelude::*;

extern {
    pub fn alert(s: &str);

pub fn greet(name: &str) {
    alert(&format!("Hello, {}!", name));

    let window = web_sys::window().expect("no global `window` exists");
    let document = window.document().expect("should have a document on window");
    let body = document.body().expect("document should have a body");

    // Manufacture the element we're gonna append
    let val = document.create_element("p");
    val.set_text_content(Some("Hello from Rust!"));


Document::create_element returns Result, so you have to handle the error case somehow. In this code, it's probably possible to just unwrap it. In more general case, it'd be useful to understand the corresponding chapter of the Book.


I find this here (web_sys::Document::create_element function)
and it's working

		let val = document.create_element("p").unwrap();
		val.set_inner_html("Hello World from WebAssemblyMan!");

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.