LEVIATHAN v962456e · 962456eee1

Standard Library

namespace Dom

The browser document surface: entry points for reaching and creating DOM nodes.

since 0.1.0-alpha.1wasm

Overview

Dom exists only when a program is built for the browser (the wasm32 target). Every function here returns a DomNode, a handle to a node that lives in the page, or a number describing the page's event listeners. Operations that do not act on an existing node, such as creating an element or looking one up by id, belong here; operations on a node are methods on DomNode.

Examples

Building a small page fragment

DomNode box = Dom::create("div");
box.setAttr("id", "app").setText("hello");
Dom::body().append(box);
console.writeln(Dom::byId("app").text());
not run — runs only on the wasm target

Functions

body

@extern("documentBody", "Node")
body() -> DomNode

The page's body element.

Returns

The document body node.

byId

@extern("getElementById", "Node")
byId(string id) -> DomNode

Find the element with the given id attribute.

Parameters

id
The id to look up.

Returns

The element, or a node whose exists() is false if none has that id.

Examples

Looking up an element

DomNode status = Dom::byId("status");
if (status.exists()) {
    status.setText("ready");
}
not run — runs only on the wasm target

See also: exists

create

@extern("createElement", "Node")
create(string t) -> DomNode

Create a new element. It is not part of the page until it is appended to a node that is.

Parameters

t
The tag name, for example "div" or "li".

Returns

The new, detached element.

Examples

Creating an element

DomNode heading = Dom::create("h1");
heading.setText("Hello");
Dom::body().append(heading);
not run — runs only on the wasm target

listenerCount

@extern("cloCount", "Int")
listenerCount() -> int

The number of event handlers currently registered with the host.

It returns to its starting value once every handler added with on or events has been removed, which makes it a convenient check for leaked handlers.

Returns

The count of live handlers.

Examples

Checking that handlers are cleaned up

DomNode button = Dom::create("button");
int token = button.on("click", (e) => {});
console.writeln(Dom::listenerCount());
button.off("click", token);
console.writeln(Dom::listenerCount());
not run — runs only on the wasm target

textNode

@extern("createTextNode", "Node")
textNode(string s) -> DomNode

Create a new text node.

Parameters

s
The text.

Returns

The new, detached text node.

See also

  • DomNode — A handle to one node in the browser page.