Skip to content

DOM

wybthon.dom

dom

Lightweight DOM wrapper utilities for Pyodide/browser environments.

This module exposes a thin Pythonic facade over the browser's DOM API, designed to feel familiar to JavaScript developers while integrating cleanly with Wybthon's reactive renderer:

  • Element wraps a single DOM node and offers ergonomic helpers for attributes, classes, styles, events, and queries.
  • Ref is a mutable container used by the renderer to hand out a reference to a mounted element.

The wrapper deliberately mirrors familiar DOM property names (e.g. value, checked, files) so that event handlers can read state exactly as they would in JavaScript:

def on_input(e):
    name(e.target.value)
See Also

Classes:

Name Description
Element

Thin wrapper around a DOM node with convenience methods.

Ref

Mutable container holding a reference to an Element.

Element

Element(tag: Optional[str] = None, existing: bool = False, node: Any = None)

Thin wrapper around a DOM node with convenience methods.

Element can be constructed in three ways:

  • With a tag name to create a brand-new node (Element("div")).
  • With a CSS selector and existing=True to wrap an existing node (Element("#root", existing=True)).
  • With an opaque node value to wrap a node returned by another API (used internally by query helpers).

The wrapper proxies common form-input properties (value, checked, files) so handlers can read state from e.target.value exactly as in React or SolidJS.

Create a new element, wrap an existing one, or wrap a raw node.

Parameters:

Name Type Description Default
tag Optional[str]

Tag name ("div") or, when existing=True, a CSS selector identifying the node to wrap.

None
existing bool

If True, query the document for tag instead of creating a new element.

False
node Any

Raw underlying DOM node to wrap. When provided, tag and existing are ignored.

None

Raises:

Type Description
ValueError

If neither node nor a usable tag is provided.

Methods:

Name Description
set_text

Replace the text content of this element.

append_to

Append this element to parent.

append

Append an Element or a text string as a child node.

remove

Detach this element from its parent (no-op if already detached).

load_html

Fetch HTML from url and assign it to innerHTML.

set_html

Replace this element's content with the provided HTML string.

set_attr

Set an attribute on this element, with text-node fallbacks.

get_attr

Return the attribute value for name, or None when absent.

remove_attr

Remove an attribute from this element.

set_style

Set CSS properties using a dict and/or keyword arguments.

add_class

Add one or more CSS classes to this element.

remove_class

Remove one or more CSS classes from this element.

toggle_class

Toggle a CSS class, optionally forcing on/off.

has_class

Return True if the element currently has the given class.

on

Add an event listener and track it for later cleanup.

off

Remove matching event listeners previously attached via on.

cleanup

Remove all tracked event listeners from this element.

query

Query a single element by CSS selector.

query_all

Query all matching elements by CSS selector.

find

Return the first matching descendant Element, or None.

find_all

Return all matching descendant elements as a list.

attach_ref

Store this element on ref.current.

Attributes:

Name Type Description
value Any

Current value of an <input>, <textarea>, or <select>.

checked bool

Checked state of a checkbox or radio input.

files Any

FileList for file inputs (<input type="file">), or None.

value property writable

value: Any

Current value of an <input>, <textarea>, or <select>.

checked property writable

checked: bool

Checked state of a checkbox or radio input.

files property

files: Any

FileList for file inputs (<input type="file">), or None.

set_text

set_text(text: str) -> None

Replace the text content of this element.

append_to

append_to(parent: Element) -> None

Append this element to parent.

append

append(child: Union[Element, str]) -> None

Append an Element or a text string as a child node.

remove

remove() -> None

Detach this element from its parent (no-op if already detached).

load_html async

load_html(url: str) -> None

Fetch HTML from url and assign it to innerHTML.

Parameters:

Name Type Description Default
url str

URL to fetch via the browser's fetch API.

required

set_html

set_html(html: str) -> None

Replace this element's content with the provided HTML string.

Caution

This bypasses the renderer's diffing and does not sanitize input. Avoid passing untrusted HTML.

set_attr

set_attr(name: str, value: Union[str, int, float, bool]) -> None

Set an attribute on this element, with text-node fallbacks.

Parameters:

Name Type Description Default
name str

Attribute name (or nodeValue/text for text nodes).

required
value Union[str, int, float, bool]

Attribute value; coerced to str.

required

get_attr

get_attr(name: str) -> Optional[str]

Return the attribute value for name, or None when absent.

remove_attr

remove_attr(name: str) -> None

Remove an attribute from this element.

set_style

set_style(styles: Optional[Dict[str, Union[str, int]]] = None, **style_kwargs: Union[str, int]) -> None

Set CSS properties using a dict and/or keyword arguments.

Parameters:

Name Type Description Default
styles Optional[Dict[str, Union[str, int]]]

Optional mapping of CSS property name to value.

None
**style_kwargs Union[str, int]

Additional CSS properties (last write wins if a key appears in both).

{}

add_class

add_class(*class_names: str) -> None

Add one or more CSS classes to this element.

remove_class

remove_class(*class_names: str) -> None

Remove one or more CSS classes from this element.

toggle_class

toggle_class(class_name: str, force: Optional[bool] = None) -> None

Toggle a CSS class, optionally forcing on/off.

Parameters:

Name Type Description Default
class_name str

Class to toggle.

required
force Optional[bool]

Pass True to ensure the class is added, False to ensure it is removed; None toggles based on the current state.

None

has_class

has_class(class_name: str) -> bool

Return True if the element currently has the given class.

on

on(event_type: str, handler: Callable[[Any], Any], *, options: Optional[Dict[str, Any]] = None) -> None

Add an event listener and track it for later cleanup.

Listeners attached through on are remembered and removed by off or cleanup. The handler is wrapped in a Pyodide proxy so it can be released on removal.

Parameters:

Name Type Description Default
event_type str

DOM event name (e.g. "click", "input").

required
handler Callable[[Any], Any]

Callback invoked with the DOM event object.

required
options Optional[Dict[str, Any]]

Optional addEventListener options (e.g. {"capture": True}).

None

off

off(event_type: Optional[str] = None, handler: Optional[Callable[[Any], Any]] = None) -> None

Remove matching event listeners previously attached via on.

Parameters:

Name Type Description Default
event_type Optional[str]

If given, only remove listeners of this type.

None
handler Optional[Callable[[Any], Any]]

If given, only remove listeners with this exact callback identity.

None

When both arguments are None, all tracked listeners are removed.

cleanup

cleanup() -> None

Remove all tracked event listeners from this element.

query classmethod

query(selector: str, within: Optional[Element] = None) -> Optional[Element]

Query a single element by CSS selector.

Parameters:

Name Type Description Default
selector str

CSS selector string.

required
within Optional[Element]

Optional parent Element to scope the query to. Defaults to document.

None

Returns:

Type Description
Optional[Element]

The first matching Element, or None if no node matches.

query_all classmethod

query_all(selector: str, within: Optional[Element] = None) -> List[Element]

Query all matching elements by CSS selector.

Parameters:

Name Type Description Default
selector str

CSS selector string.

required
within Optional[Element]

Optional parent Element to scope the query to. Defaults to document.

None

Returns:

Type Description
List[Element]

A list of wrapped Element instances (possibly empty).

find

find(selector: str) -> Optional[Element]

Return the first matching descendant Element, or None.

find_all

find_all(selector: str) -> List[Element]

Return all matching descendant elements as a list.

attach_ref

attach_ref(ref: Ref) -> None

Store this element on ref.current.

Ref

Ref()

Mutable container holding a reference to an Element.

Instantiate with Ref() and pass to elements via the ref= prop. After mount, ref.current points at the wrapped element; after unmount, it is reset to None.

Example
from wybthon import Ref, on_mount
from wybthon.html import input_

input_ref = Ref()

def focus_on_mount():
    on_mount(lambda: input_ref.current and input_ref.current.element.focus())

input_(type="text", ref=input_ref)

Initialize an empty ref pointing at None.