How to Use web-sys for DOM Manipulation from Rust

Web
Use the `wasm-bindgen` crate to generate safe Rust bindings for the browser DOM, then call methods on `web_sys` types like `Document` and `Element`.

How to Use web-sys for DOM Manipulation from Rust

Use the wasm-bindgen crate to generate safe Rust bindings for the browser DOM, then call methods on web_sys types like Document and Element.

use wasm_bindgen::prelude::*;
use web_sys::{Document, HtmlElement, Window};

#[wasm_bindgen(start)]
pub fn main() {
    let window = web_sys::window().expect("no global window");
    let document = window.document().expect("no document on window");
    let body = document.body().expect("no body on document");
    let div = document.create_element("div").expect("failed to create element");
    div.set_text_content(Some("Hello from Rust!"));
    body.append_child(&div).expect("failed to append child");
}

Add wasm-bindgen and web-sys to Cargo.toml with the default and document features:

[dependencies]
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = ["Document", "HtmlElement", "Window"] }

Compile to WebAssembly using wasm-pack:

wasm-pack build --target web

Include the generated JavaScript glue code in your HTML file to load the Rust module.