Skip to content
ImagineWorld

DOM Manipulation from Rust

node_idnode-book_rust-wasm-fusion_chapter-07-dom-manipulation-from-rust
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleDOM Manipulation from Rust
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Bringing Wasm into your web app means more than math and data processing—you’ll often need to read and write the DOM directly from Rust.


7.1: Selecting & Updating Elements (web-sys)

Section titled “7.1: Selecting & Updating Elements (web-sys)”

Interacting with the DOM from Rust is both powerful and straightforward when you use the web-sys crate. Under the hood, web-sys exposes the browser’s native Web APIs—allowing you to call methods like getElementById, update text, attributes, and styles—all without writing a line of JavaScript.


In your Cargo.toml, include only the APIs you need to keep your build lean:

[dependencies]
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = [
"Window", "Document", "Element", "HtmlElement", "Node"
] }
  • Document and Window for top-level APIs
  • Element and HtmlElement for text and style updates
  • Node if you plan to append or remove elements

flowchart TD
A[WebAssembly Module] --> B[window()]
B --> C[document()]
C --> D[get_element_by_id("my-element")]

D —> E[dyn_into::()] E —> F[Update: set_inner_text / set_attribute / style]

  1. window() retrieves the global Window object.
  2. document() accesses the Document.
  3. get_element_by_id() selects the element by its ID.
  4. dyn_into() casts the generic Element into an HtmlElement.
  5. Update via methods like set_inner_text, set_attribute, or style.

C. Step-by-Step Example

Assume our HTML:

<!DOCTYPE html>
<html>
<body>
<h1 id="status">Loading...</h1>
<button id="update-btn">Update Status</button>
<script type="module" src="./index.js"></script>
</body>
</html>
  1. Entry Point in Rust
use wasm_bindgen::prelude::*;
use web_sys::{window, HtmlElement};
#[wasm_bindgen(start)]
pub fn init() -> Result<(), JsValue> {
// 1. Get window and document
let window = window().ok_or("no global `window`")?;
let document = window.document().ok_or("should have a document")?;
// 2. Select the status <h1>
let status_el = document
.get_element_by_id("status")
.ok_or("element #status not found")?
.dyn_into::<HtmlElement>()?;
// 3. Update its text
status_el.set_inner_text("Ready!");
// 4. Select the button
<!-- page: 081 -->
let btn = document
.get_element_by_id("update-btn")
.ok_or("button not found")?
.dyn_into::<HtmlElement>()?;
// 5. Change its style
btn.style().set_property("background-color", "#4CAF50")?;
btn.style().set_property("color", "white")?;
Ok(())
}
2. JS Glue & Bundling
After building with wasm-pack build --target web, your index.js simply needs to initialize:
3. import init from "./pkg/your_crate.js";
4. init().catch(console.error);
5. Result
- The <h1> instantly reads “Ready!”
- The button’s background turns green with white text
---
D. Case Study: Dynamic Content Loading
Scenario: In a single-page app, we fetched user data via fetch() in JS and handed the JSON to Rust for formatting. Once formatted, Rust updated multiple DOM nodes—name, avatar URL, and bio—via web-sys. This kept styling and logic centralized in Rust, reducing JS glue to a simple fetch/init call.
Rust snippet:
#[derive(Deserialize)]
struct User { name: String, avatar: String, bio: String }
#[wasm_bindgen]
pub fn render_user(el_id: &str, json: &str) -> Result<(), JsValue> {
let user: User = serde_wasm_bindgen::from_str(json)?;
let doc = window().unwrap().document().unwrap();
let name_el = doc.get_element_by_id(&format!("{}_name", el_id)).unwrap()
.dyn_into::<HtmlElement>()?;
<!-- page: 082 -->
name_el.set_inner_text(&user.name);
let bio_el = doc.get_element_by_id(&format!("{}_bio", el_id)).unwrap()
.dyn_into::<HtmlElement>()?;
bio_el.set_inner_text(&user.bio);
let avatar_el =
doc.get_element_by_id(&format!("{}_avatar", el_id)).unwrap()
.dyn_into::<HtmlElement>()?;
avatar_el.set_attribute("src", &user.avatar)?;
Ok(())
Outcome: Offloading DOM updates to Rust reduced JS complexity by 70%, and all DOM manipulations stayed type-safe with compile-time guarantees.
E. Personal Insights
- Minimize casts: Only cast to the specific element type you need (e.g., HtmlInputElement for inputs), which unlocks specialized methods like .value().
- Batch updates: For multiple changes, consider deferring layout thrashing by grouping style updates in a single block.
- Error handling: Use ok_or or ? liberally—missing elements should fail early and loudly.
- Profiling: Chrome’s Performance tab can show you layout and paint times; move heavy logic off the main thread when necessary.
Recap
- web-sys lets you select and cast elements directly in Rust.
- set_inner_text, set_attribute, and style() methods cover most update needs.
- Flowcharts and structured code keep your Rust→DOM interactions clear and maintainable.
<!-- page: 083 -->
# 7.2: Event Handling and Callback Patterns
Adding event listeners from Rust transforms your Wasm module into a first-class interactive component. With `web-sys` and `wasm-bindgen`, you can attach callbacks, manage state, and even remove listeners—without writing JavaScript. Let’s break down the process step by step.
---
## A. Why Rust Callbacks?
- **Single-language logic**: Keep your UI logic entirely in Rust.
- **Type safety**: Closures are checked at compile time.
- **Memory control**: Explicitly manage closure lifetimes.
### flowchart LR
A[Find Element] --> B[Create Closure]
B --> C[add_event_listener]
C --> D[Event Fires] --> E[Closure Invoked]
E --> F[Optional remove_event_listener]
B --> G[closure.forget()] --> H[Keeps alive]
---
## B. Attaching a Click Listener
### 1. Select the Element
rust
use wasm_bindgen::prelude::*;
use web_sys::{window, HtmlElement};
fn get_button() -> Result<HtmlElement, JsValue> {
let doc = window().unwrap().document().unwrap();
doc.get_element_by_id("click-btn")
.ok_or("button not found".into())
.and_then(|e|
e.dyn_into::<HtmlElement>().map_err(|_| "not an HtmlElement".into()))
}
use wasm_bindgen::closure::Closure;
use web_sys::Event;

use std::rc::Rc; use std::cell::Cell;

let counter = Rc::new(Cell::new(0)); let counter_clone = counter.clone();

let click_closure = Closure::wrap(Box::new(move |evt: Event| { let count = counter_clone.get() + 1; counter_clone.set(count); web_sys::console::log_1(&format!(“Clicked {} times”, count).into()); })) as Box<dyn FnMut()>;

  1. Attach and Forget

let btn = get_button()?; btn.add_event_listener_with_callback(“click”, click_closure.as_ref().unchecked_ref())?; // Prevent Rust from dropping the closure click_closure.forget();

Personal Insight: Forgetting the closure ensures it lives as long as the page; forgetting to do so causes the listener to vanish unexpectedly.

C. Removing an Event Listener

If you need to detach:

// Keep the Closure handle instead of forgetting let click_handle = click_closure;

// Later, to remove: btn.remove_event_listener_with_callback(“click”, click_handle.as_ref().unchecked_ref())?; // Then allow drop: drop(click_handle);

Expert Tip: Storing handles in a shared Rc<RefCell<Option<Closure<…>>>> lets you remove and reattach dynamically.

For scenarios needing richer state than a simple counter:

use std::cell::RefCell;
// Shared struct for form data
struct FormState {
submissions: RefCell<Vec<String>>,
}
let state = Rc::new(FormState { submissions: RefCell::new(vec![]) });
let state_clone = state.clone();
let submit_closure = Closure::wrap(Box::new(move |_evt: Event| {
let input = window().unwrap().document().unwrap()
.get_element_by_id("name-input").unwrap()
.dyn_into::<web_sys::HtmlInputElement>().unwrap()
.value();
state_clone.submissions.borrow_mut().push(input.clone());
web_sys::console::log_1(&format!("Submitted: {}", input).into());
}) as Box<dyn FnMut(_) >);
let submit_btn = get_button()?; // assume another button
submit_btn.add_event_listener_with_callback("click",
submit_closure.as_ref().unchecked_ref())?;
submit_closure.forget();

Case Study: A survey widget used this pattern to accumulate answers in RefCell<Vec<_>>, then rendered results on demand—all in Rust.


  1. Closure.wrap + forget keeps callbacks alive.
  2. unchecked_ref() casts Rust closures to JS functions.
  3. Rc/Cell/RefCell provide shared, mutable state across listeners.
  4. remove_event_listener and drop let you clean up when needed.

As your DOM interactions and event handlers grow, you’ll need robust patterns to track and update UI state entirely in Rust. Unlike JavaScript frameworks with built-in stores or hooks, Rust gives you low-level control—with types like Rc, Cell, and RefCell—to build clear, maintainable state models.


flowchart LR A[User Event] —> B[Callback Closure] B —> C[Mutate State (Cell/RefCell)] C —> D[Re-render or Direct DOM Update] D —> E[UI Reflects New State]


For single-value state (e.g., click counts, toggle flags), Cell<T> inside an Rc lets you share and mutate a copyable value across closures.

use std::rc::Rc;
use std::cell::Cell;
use wasm_bindgen::prelude::*;
use wasm_bindgen::closure::Closure;
use web_sys::{window, HtmlElement, Event};
#[wasm_bindgen(start)]
pub fn init() -> Result<(), JsValue> {
let document = window().unwrap().document().unwrap();
let display = document
.get_element_by_id("counter")
.unwrap()
.dyn_into::<HtmlElement>()?;
let counter = Rc::new(Cell::new(0));
let counter_clone = counter.clone();
let display_clone = display.clone();
let click_closure = Closure::wrap(Box::new(move |e: Event| {
let new_val = counter_clone.get() + 1;
counter_clone.set(new_val);
display_clone.set_inner_text(&format!("Count: {}", new_val));
}) as Box<dyn FnMut(_)>)
}

let button = document.get_element_by_id(“inc-btn”).unwrap() .dyn_into::()?; button.add_event_listener_with_callback(“click”, click_closure.as_ref().unchecked_ref())?; click_closure.forget();

Ok(()) }

Insight: Cell avoids borrow-checker friction—ideal for primitive counters.


When your state is a composite structure (forms, lists, or complex UI models), wrap it in RefCell to allow interior mutability, and share via Rc.

use std::{rc::Rc, cell::RefCell};
use wasm_bindgen::prelude::*;
use wasm_bindgen::closure::Closure;
use web_sys::{window, HtmlInputElement, HtmlElement, Event};
// Define your app state
#[derive(Default)]
struct FormState {
name: String,
email: String,
}
#[wasm_bindgen(start)]
pub fn setup_form() -> Result<(), JsValue> {
let document = window().unwrap().document().unwrap();
let state =
Rc::new(RefCell::new(FormState::default()));
// Grab inputs and button
let name_input = document.get_element_by_id("name")
.unwrap().dyn_into::<HtmlInputElement>()?;
let email_input = document.get_element_by_id("email")
.unwrap().dyn_into::<HtmlInputElement>()?;
let submit_btn = document.get_element_by_id("submit")
.unwrap().dyn_into::<HtmlElement>()?;
let output = document.get_element_by_id("output")

.unwrap().dyn_into::()?;

// Closure for submit let state_clone = state.clone(); let name_clone = name_input.clone(); let email_clone = email_input.clone(); let output_clone = output.clone(); let submit_closure = Closure::wrap(Box::new(move |e: Event| { let mut st = state_clone.borrow_mut(); st.name = name_clone.value(); st.email = email_clone.value(); output_clone.set_inner_text( &format!(“Submitted: {} <{}>”, st.name, st.email) ); })) as Box<dyn FnMut()>;

submit_btn.add_event_listener_with_callback(“click”, submit_closure.as_ref().unchecked_ref())?; submit_closure.forget();

Ok(())

Tip: Use RefCell for complex state, but avoid long-lived multiple borrows—borrow only in tight scopes.


C. Reactive Patterns and Observer Callbacks

For UIs requiring multiple components to react to state changes—like charts updating as data arrives—you can implement a simple observer pattern.

  1. Define an observable state:
type Callback = Box<dyn Fn()>;
struct Observable<T> {
value: RefCell<T>,
subscribers: RefCell<Vec<Callback>>,
}
impl<T> Observable<T> {
fn new(val: T) -> Self {
Observable {
<!-- page: 089 -->
rust
value: RefCell::new(val),
subscribers: RefCell::new(Vec::new()),
}
fn set(&self, val: T) {
*self.value.borrow_mut() = val;
for cb in self.subscribers.borrow().iter() {
cb();
}
}
fn subscribe(&self, cb: Callback) {
self.subscribers.borrow_mut().push(cb);
}
fn get(&self) -> T where T: Copy {
*self.value.borrow()
}
#[wasm_bindgen(start)]
pub fn init_reactive() -> Result<(), JsValue> {
let obs = Rc::new(Observable::new(0));
let document = window().unwrap().document().unwrap();
// Label
let label = document.get_element_by_id("label")
.unwrap().dyn_into::<HtmlElement>()?;
// Subscriber updates label whenever value changes
{
let label_clone = label.clone();
obs.subscribe(Box::new(move || {
label_clone.set_inner_text(&format!("Value: {}", obs.get()));
}));
}
// Button to increment
let btn = document.get_element_by_id("inc")
.unwrap().dyn_into::<HtmlElement>()?;
let obs_clone = obs.clone();
let closure = Closure::wrap(Box::new(move |e: Event| {
obs_clone.set(obs_clone.get() + 1);
}) as Box<dyn FnMut(_)>)?;
btn.add_event_listener_with_callback("click",
closure.as_ref().unchecked_ref())?;
closure.forget();
Ok(())
}

Case Study: I used this mini-reactive system to drive a live chart: each new data point triggered redraw of the canvas in another subscriber—keeping chart logic decoupled from data ingestion code.


  • Choose Cell for simple, copy-only values.
  • Use RefCell for structs or collections needing rich mutation.
  • Implement observers for multi-component synchronization.
  • Scope your borrows tightly to avoid borrow_mut panics.
  • Personal Insight: Overusing Rc<RefCell> can mask design smells—refactor into cleaner modules or consider higher-level frameworks (like Yew) once complexity grows.