ElementNode

Core node representing a single HTML element in the Domphy tree.

import { ElementNode } from "@domphy/core"

const node = new ElementNode({ div: "Hello World" })
node.render(document.body)

Constructor

new ElementNode(domphyElement: DomphyElement, parent?: ElementNode | null)

Properties

PropertyTypeDescription
typestringAlways "ElementNode"
parentElementNode | nullParent node. null if root
tagNameTagNameHTML tag name e.g. "div"
childrenElementListChild nodes
stylesStyleListScoped CSS styles
attributesAttributeListHTML attributes
domElementHTMLElement | nullMounted DOM element
keystring | number | nullIdentity key for diffing
nodeIdstringHash used for scoped CSS class generation
pathIdstringHash of the node path in the tree
_portal((root) => Element) | undefinedRedirects DOM mount target when present

The scoped CSS class is attached through node.attributes using the pattern ${tagName}_${nodeId}.

Methods

render(domElement)

Creates a DOM node and appends it to the target.

node.render(document.body)
node.render(document.getElementById("app")!)

mount(domElement, domStyle?)

Hydrates onto an existing DOM element. Used for SSR.

const html = node.generateHTML()
const css = node.generateCSS()
// ... send to client ...
const domStyle = document.getElementById("domphy-style") as HTMLStyleElement
node.mount(document.getElementById("app")!, domStyle)

When doing SSR, render CSS into on the server, then pass that same style element to mount() on the client.

remove()

Removes this node from its parent.

node.remove()

merge(partial)

Updates this node from a partial element descriptor.

node.merge({ style: { color: "red" }, class: "active" })

addEvent(name, callback)

Registers a DOM event listener. Multiple callbacks are chained.

node.addEvent("click", (e, node) => console.log(node.tagName))

addHook(name, callback)

Registers a lifecycle hook. Multiple callbacks are chained.

node.addHook("Mount", (node) => console.log("mounted"))
node.addHook("BeforeRemove", (node, done) => {
  animate(node.domElement).then(done)
})
HookTrigger
InsertNode added to children list
MountDOM element created
BeforeUpdateBefore children diff
UpdateAfter children diff
BeforeRemoveBefore DOM removal — call done() to proceed
RemoveAfter DOM removal

getRoot()

Returns the root node of the tree.

const root = node.getRoot()

getContext(name) / setContext(name, value)

Inherited context — walks up the tree to find the nearest value.

// Parent
node.setContext("theme", "dark")

// Any descendant
const theme = node.getContext("theme") // "dark"

getMetadata(name) / setMetadata(key, value)

Local metadata — not inherited by children.

node.setMetadata("id", "user-123")
node.getMetadata("id") // "user-123"

generateHTML()

Generates HTML string. Used for SSR.

const html = node.generateHTML()
// "<div class="div_abc123">Hello</div>"

generateCSS()

Generates CSS string for this node and all descendants. Used for SSR.

const css = node.generateCSS()