dom

domonic’s DOM aims to be useful as an actual platform surface, not just a tree of helper objects.

That is intentional. A Python developer can practise the browser DOM API in Python: createElement(), appendChild(), removeChild(), querySelector(), querySelectorAll(), parentNode, childNodes and textContent are the same concepts used in JavaScript in the browser.

For JavaScript developers, this means domonic DOM code is recognisable even inside Python. You can parse or generate markup, then keep using familiar operations such as querySelector(), appendChild(), removeChild(), setAttribute() and dispatchEvent().

To use the DOM, either reference your own root html node or import the global document from domonic.dom.

# Access the document via the html tag.
mydom = html()
# mydom.getElementbyID...

# Or import the document global.
from domonic.dom import document
# document.createElement...
print(document)

The last html() created becomes the active document. You can also set it manually, but it must be a Document instance. Before an html class is created, domonic keeps an empty document around so static methods are available.

Remember that Python globals are module-local. Import document again after creating an html root if another module or function needs the updated document:

print(document)
d = html(body("Hello"))
print(document)  # no change
print('body1', d.doctype)
print('body2', domonic.dom.document.doctype)
print('body3', document.doctype)
from domonic.dom import document  # Re-import to get the updated document.
print('body4', document.doctype)

Notice that before re-importing it was still the previous object.

In most cases, use your own root node directly. The global document is useful when you need access from a different module.

createElement

Here’s an example of creating your own elements using the DOM API:

from domonic.html import html
from domonic.dom import document

site = html()
el = document.createElement('myelement')
site.appendChild(el)
print(site)
# <html><myelement></myelement></html>

querySelectorAll

querySelectorAll and querySelector are useful for finding elements in the DOM.

These use familiar CSS selector strings, so the same selectors can be reused in browser JavaScript, tests, scraping scripts, and domonic server-side rendering.

from domonic import domonic

mysite = domonic.parseString(
    '<div>'
    '<button class="fa-twitter">Follow</button>'
    '<a href="#services">Services</a>'
    '<a rel="nofollow" href="https://twitter.com/technology">Twitter</a>'
    '</div>'
)

mysite.querySelectorAll('button')             # [<button class="fa-twitter">]
mysite.querySelectorAll('.fa-twitter')        # [<button class="fa-twitter">]
mysite.querySelectorAll("a[rel=nofollow]")            # [<a rel="nofollow" ...>]
mysite.querySelectorAll("a[href='#services']")        # [<a href="#services">]
mysite.querySelectorAll("a[href$='technology']")      # [<a rel="nofollow" ...>]

somelinks = mysite.querySelectorAll("a[href*='twitter']")
for l in somelinks:
        print(l.href)
# https://twitter.com/technology

See the examples folder for other uses of the Python virtual DOM.

querySelectorAll returns a static list – a snapshot. The collections from getElementsByTagName, getElementsByTagName("*"), getElementsByClassName and getElementsByName are live: they re-scan the tree on every access, so a collection handed out early reflects elements added or removed afterwards (DOM spec). getElementsByTagName matches the qualified name literally (ASCII case-insensitively) and never raises – an argument that is not a tag name, such as "a.b" or "", just matches nothing. Out-of-range indexing returns None.

Behind these, getElementById, getElementsBy* and querySelector / querySelectorAll are backed by lazily-built indexes: the first call over a tree builds an id map and tag / class / attribute maps on the root, and later calls answer from those until a mutation invalidates them. This is transparent – results always reflect the current tree, live collections stay live – and a tree that is only built and rendered, never queried, builds no index. See Parser Performance for the query-performance picture.

Tree mutation errors

appendChild(), insertBefore() and replaceChild() reject an insertion that would place a node inside itself or inside one of its own descendants – that would build a cycle and hang every later traversal. The rejection is a DOMException whose name is "HierarchyRequestError", matching the browser. insertBefore() with a reference node that is not a child raises a DOMException named "NotFoundError".

from domonic.dom import Document, DOMException

doc = Document()
parent = doc.createElement("parent")
child = doc.createElement("child")
parent.appendChild(child)

try:
        child.appendChild(parent)
except DOMException as exc:
        print(exc.name)   # HierarchyRequestError
        print(exc.code)   # 3  (the legacy numeric code is still available)

DOMException subclasses ValueError for backwards compatibility – domonic historically raised a plain ValueError here – so existing except ValueError code keeps working. It can be constructed either browser-style, DOMException(message, name), or with the legacy DOMException(code, message) form.

compareDocumentPosition

node.compareDocumentPosition(other) returns the DOM spec’s combined bitmask, not a single flag: an ancestor is DOCUMENT_POSITION_CONTAINS | DOCUMENT_POSITION_PRECEDING (10), a descendant is DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING (20), and two nodes in different trees give DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC plus a PRECEDING / FOLLOWING direction bit that is stable for the pair and reverses when the arguments are swapped. Test the result with &:

pos = a.compareDocumentPosition(b)
if pos & Node.DOCUMENT_POSITION_CONTAINED_BY:
    ...  # b is inside a

Serialising: str() vs innerHTML / outerHTML

str(node) produces domonic’s authoring-style markup: void elements are self-closed (<br/>), boolean attributes render bare (checked), and < / > are escaped inside attribute values. This is stable and is what most server-side rendering wants.

innerHTML, outerHTML and getHTML() instead follow the WHATWG HTML fragment serialisation algorithm, so their output is byte-compatible with a browser: <br> (no slash), checked="", and only &, " and the non-breaking space escaped in attribute values. Reach for these when a port or a test diffs against real browser output.

from domonic.html import div, br, input as input_

el = div(input_(_type="checkbox", _checked=""), br(), _title="a<b>")

str(el)
# <div title="a&lt;b&gt;"><input type="checkbox" checked/><br/></div>

el.outerHTML
# <div title="a<b>"><input type="checkbox" checked=""><br></div>

Rendering behaviour of str(node) is configurable through DOMConfig (below); the fragment serialisation is not.

<script> / <style> and the other HTML “raw text” elements are always serialised verbatim in every one of these forms – their text content is never entity-escaped, matching a browser (escaping it would change what the script actually executes):

from domonic.dom import DOMParser

doc = DOMParser().parseFromString(
    '<html><body><script>if (a && b) x("y");</script></body></html>'
)
print(str(doc.body))
# <body><script>if (a && b) x("y");</script></body>

Parsing documents and pretty-printing

DOMParser().parseFromString(markup, "text/html") parses a complete HTML document with html5lib, including implied html, head and body elements. domonic.parseString(markup) retains fragment-oriented behavior for snippets; pass document=True to request the same full-document mode. Other explicit backends can differ in their HTML error recovery. If a backend returns content without an HTML root for input containing an HTML doctype, domonic reparses it with html5lib rather than discarding the content.

Parsing does not invent a title or add indentation. str(doc) serializes the document compactly, including a supplied doctype; doc.documentElement.outerHTML serializes the root element without the doctype. Use format(doc) for human-readable indentation. Add an empty title explicitly if desired:

from domonic.dom import DOMParser
from domonic.html import title

doc = DOMParser().parseFromString(
    "<!DOCTYPE html><div>Hello World</div>", "text/html"
)
doc.head.appendChild(title(""))
print(format(doc).expandtabs(2).strip())

Pretty-printing is intended for display: inserted whitespace can affect text layout, so use compact serialization when preserving text spacing matters.

Doctypes

Document.doctype is None unless a doctype was parsed from the source or set explicitly – it is no longer synthesised on read. Parsing markup that contains <!DOCTYPE ...> sets it, and document.implementation.createHTMLDocument() creates one (<!DOCTYPE html>), matching the DOM spec.

When building a full page programmatically, ask the html tag for a doctype with the _doctype keyword:

from domonic.html import html, head, body, h1

page = html(head(), body(h1("Hi")), _doctype=True)          # <!DOCTYPE html>
page = html(head(), body(), _doctype="XHTML1_1")            # a domonic.constants.doctypes key
page = html(head(), body(), _doctype="<!DOCTYPE html>")     # a literal string

str(page) and format(page) then both emit the doctype ahead of <html>. Without the keyword html() renders as <html>...</html> and page.doctype is None. Equivalently, assign page.doctype = DocumentType("html", "", "") after construction.

tagName, nodeName and localName

Per the DOM spec, an HTML element’s tagName / nodeName are upper-cased when the element came from parsing HTML (SVG, MathML, and XML keep their original case); localName is always lower-case:

from domonic import domonic

page = domonic.parseString("<div><p>hi</p><svg><circle/></svg></div>")
page.tagName                          # 'DIV'
page.querySelector("p").tagName       # 'P'
page.querySelector("p").localName     # 'p'
page.querySelector("svg").tagName     # 'svg'  (SVG keeps its case)

Elements you build yourself (div(), document.createElement(...)) are not associated with an HTML document the way a parsed tree is, so their tagName stays lower-case:

from domonic.html import div

div().tagName   # 'div'

dataset

element.dataset reflects an element’s data-* attributes both as a mapping and as JavaScript-style attribute access:

from domonic.html import div

el = div()
el.dataset.userId = "42"       # same as el.setAttribute("data-user-id", "42")
print(el)                      # <div data-user-id="42"></div>
print(el.dataset.userId)       # '42'
print(el.dataset["userId"])    # '42'
print(el.dataset.missing)      # None (JS: undefined)

classList

element.classList is a live DOMTokenList over the class attribute. It follows the DOM spec: add() / remove() / toggle() / replace() throw DOMException("SyntaxError") for an empty token and DOMException("InvalidCharacterError") for a token containing an ASCII space, and validate every argument before touching the attribute. contains() never throws – an empty or whitespace-containing token simply is not present. toString() returns the attribute value verbatim (not normalised), out-of-range indexing returns None (JS undefined), and supports() always raises TypeError because classList has no defined token set.

from domonic.html import div

el = div(_class="  a  a b ")
el.classList.toString()          # '  a  a b '  (verbatim)
list(el.classList)               # ['a', 'b']   (the token set is normalised)
el.classList.replace("a", "c")   # True  ->  class="c b"
el.classList.toggle("c", True)   # no-op force toggle leaves class="c b" untouched

DOMConfig

DOMConfig controls rendering options on the DOM.

For example, here we set several flags away from their defaults:

from domonic.html import *
from domonic.dom import DOMConfig
DOMConfig.GLOBAL_AUTOESCAPE = True
DOMConfig.HTMX_ENABLED = True
DOMConfig.RENDER_OPTIONAL_CLOSING_TAGS = False
print(html(head(),body(div(h1('heading'),div(button('hi & hack',_get='/get_hi'))))))
# <html><head><body><div><h1>heading</h1><div><button data-hx-get="/get_hi">hi &amp; hack</button></div></div>

When DOMConfig.HTMX_ENABLED is set (as above), domonic maps HTMX-style shortcut attributes to the configurable data-hx- secondary prefix recognised by HTMX – the rest of the examples on this page assume it stays set:

button(
    "Save",
    _post="/items",
    _target="#items",
    _swap_oob=True,
    **{"_on:click": "this.classList.add('busy')"},
)
# <button data-hx-post="/items" data-hx-target="#items" data-hx-swap-oob="true" data-hx-on:click="this.classList.add('busy')">Save</button>

HTMX 4 explicit inheritance can be written with the literal attribute spelling or with __inherited as a Python-friendly suffix:

div(_confirm__inherited="Are you sure?", _headers__inherited='{"X-CSRF": "token"}')
# <div data-hx-confirm:inherited="Are you sure?" data-hx-headers:inherited="{&quot;X-CSRF&quot;: &quot;token&quot;}"></div>

HTMX 4 attributes and popular extension attributes are available as shortcuts, including _query, _pending, _status, _ignore, _morph_skip, _morph_skip_children, _preload, _live, _optimistic, _targets, _download, and _multipart.

<hx-partial> responses can be generated with hx_partial:

hx_partial(div("New message"), **{"_hx-target": "#messages", "_hx-swap": "beforeend"})
# <hx-partial hx-target="#messages" hx-swap="beforeend"><div>New message</div></hx-partial>

Raw HTMX attributes can still be emitted by spelling the attribute explicitly:

button("Load", **{"_hx-get": "/items"})
# <button hx-get="/items">Load</button>

Legacy SSE and WebSocket extension spellings are still supported for existing HTMX 2 integrations:

div(_ext="sse", _sse_connect="/events", _sse_swap="message")
# <div data-hx-ext="sse" sse-connect="/events" sse-swap="message"></div>

ValidityState

Form controls expose validity, validationMessage, willValidate, checkValidity(), reportValidity(), and setCustomValidity() for server-side constraint checks.

from domonic.html import input

email = input(_type="email", _required=True, _value="not-an-email")
print(email.validity.typeMismatch)
# True
print(email.validationMessage)
# Please enter a valid value.

Render Caching

DOMConfig.RENDER_CACHE_ENABLED caches str(node)’s rendered output per node. It is off by default – turning it on is a pure opt-in with no other behaviour change.

from domonic.html import div, p
from domonic.dom import DOMConfig

DOMConfig.RENDER_CACHE_ENABLED = True

page = div(p("hello", _class="intro"))
first = str(page)   # walks the tree and renders, as normal
second = str(page)  # returns the cached string -- no re-render

The cache is invalidated automatically by the same mutation tracking MutationObserver already relies on, so appendChild(), removeChild(), setAttribute(), textContent assignment and .style changes anywhere in the subtree all correctly force a fresh render on the next str() call:

page.querySelector("p").setAttribute("id", "x")
print(str(page))
# <div><p class="intro" id="x">hello</p></div>

A change to a rendering-relevant DOMConfig flag (GLOBAL_AUTOESCAPE, RENDER_OPTIONAL_CLOSING_TAGS, HTMX_ENABLED, ALPINE_ENABLED, ATTRIBUTE_QUOTES, …) also invalidates every cached render, even with no tree mutation at all, since it changes what the same tree should render as.

This is a real win specifically for read-heavy, write-light trees – something rendered many times between occasional changes (a cached page, a dashboard, a report). It does not speed up a mutate-then-render-immediately pattern: any change still costs a full render on the next str() call, the same as with the flag off.

DOMMatrix

DOMMatrix / DOMPoint / DOMRect implement the CSS/SVG geometry interfaces: 2D and 3D affine transforms, composition, inversion, and transforming points. Composition follows the spec’s post-multiply rule – a.multiplySelf(b) (and chaining a.translateSelf(...).rotateSelf(...)) transforms a point as a.transformPoint(b.transformPoint(p)), so the last-chained operation is the one applied to the point first:

from domonic.dom import DOMMatrix, DOMPoint

m = DOMMatrix().translateSelf(10, 0).rotateSelf(90)
print(m.toString())
# matrix(0, 1, -1, 0, 10, 0)

p = m.transformPoint(DOMPoint(1, 0))
print(p.x, p.y)
# 10.0 1.0  (rotate is applied first, then the translate)

getComputedStyle(el).getPropertyValue("transform") uses the same matrix type, composing a CSS transform list the way a browser does – see styles.

The full list of available DOM methods are listed below…

domonic.dom

The core DOM implementation for domonic.

This module provides the document tree, node and element types, collections, range and selection helpers, geometry interfaces, mutation and layout observers, and the document-facing APIs that the rest of the package builds on. It is intended to feel like a practical Python surface for the DOM and related web-platform concepts rather than a small HTML helper tree.

class domonic.dom.RawHTML[source]

Bases: str

Explicitly trusted HTML child content; attributes still escape normally.

This is a trust marker, not a sanitizer. Never wrap untrusted input.

class domonic.dom.DOMConfig[source]

Bases: object

Global rendering and behaviour flags for domonic’s DOM.

DOMConfig controls how trees are rendered and how a few optional behaviours are interpreted across the library, such as auto-escaping text content and optional closing-tag handling.

GLOBAL_AUTOESCAPE: bool = False
RENDER_OPTIONAL_CLOSING_TAGS: bool = True
RENDER_OPTIONAL_CLOSING_SLASH: bool = True
SPACE_BEFORE_OPTIONAL_CLOSING_SLASH: bool = False
HTMX_ENABLED: bool = False
ALPINE_ENABLED: bool = False
ATTRIBUTE_QUOTES: bool | str | None = '"'
RENDER_CACHE_ENABLED: bool = False
domonic.dom.HTMX_ATTRIBUTES: frozenset[str] = frozenset({'boost', 'confirm', 'delete', 'disable', 'disabled_elt', 'disinherit', 'download', 'encoding', 'ext', 'get', 'headers', 'history', 'history_elt', 'ignore', 'include', 'indicator', 'inherit', 'live', 'morph_skip', 'morph_skip_children', 'multipart', 'optimistic', 'params', 'patch', 'pending', 'post', 'preload', 'preserve', 'prompt', 'push_url', 'put', 'query', 'replace_url', 'request', 'select', 'select_oob', 'status', 'swap', 'swap_oob', 'sync', 'target', 'targets', 'trigger', 'validate', 'vals', 'vars'})

Stable HTMX shortcut attributes supported by DOMConfig.HTMX_ENABLED.

These are supplied without the hx prefix, for example _get="/items" or _swap_oob=True. They render as data-hx-* secondary attributes by default, which HTMX supports via its configurable secondary prefix.

domonic.dom.HTMX_LEGACY_ATTRIBUTES: frozenset[str] = frozenset({'sse', 'ws'})

Legacy HTMX 1 shortcuts retained for backwards-compatible rendering.

domonic.dom.HTMX_EXTENSION_ATTRIBUTES: dict[str, str] = {'sse_close': 'sse-close', 'sse_connect': 'sse-connect', 'sse_swap': 'sse-swap', 'ws_connect': 'ws-connect', 'ws_send': 'ws-send'}

Legacy HTMX extension attributes that are not prefixed with hx-.

domonic.dom.ALPINE_DIRECTIVES: frozenset[str] = frozenset({'bind', 'cloak', 'collapse', 'data', 'effect', 'for', 'html', 'id', 'if', 'ignore', 'init', 'intersect', 'mask', 'model', 'modelable', 'on', 'ref', 'resize', 'show', 'sort', 'teleport', 'text', 'transition', 'trap'})

Alpine.js directives recognised by DOMConfig.ALPINE_ENABLED.

With that flag on, keyword arguments beginning with x_ whose first segment is one of these directives are rendered as x- attributes: a double underscore becomes : and remaining single underscores become -. So x_data renders x-data and x_on__click renders x-on:click. Directive modifiers that need a . (x-on:keyup.enter) still require the **{"x-on:keyup.enter": ...} form, as does the @/: shorthand.

class domonic.dom.ValidityState(element)[source]

Bases: object

Represents the constraint-validation state for a form control.

property badInput: bool
property customError: bool
property patternMismatch: bool
property rangeOverflow: bool
property rangeUnderflow: bool
property stepMismatch: bool
property tooLong: bool
property tooShort: bool
property typeMismatch: bool
property valid: bool
property valueMissing: bool
class domonic.dom.Node(*args, **kwargs)[source]

Bases: EventTarget

An abstract base class upon which many other DOM API objects are based

name: str
ELEMENT_NODE: int = 1
TEXT_NODE: int = 3
CDATA_SECTION_NODE: int = 4
PROCESSING_INSTRUCTION_NODE: int = 7
COMMENT_NODE: int = 8
DOCUMENT_NODE: int = 9
DOCUMENT_TYPE_NODE: int = 10
DOCUMENT_FRAGMENT_NODE: int = 11
DOCUMENT_POSITION_DISCONNECTED: int = 1
DOCUMENT_POSITION_PRECEDING: int = 2
DOCUMENT_POSITION_FOLLOWING: int = 4
DOCUMENT_POSITION_CONTAINS: int = 8
DOCUMENT_POSITION_CONTAINED_BY: int = 16
DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: int = 32
ATTRIBUTE_NODE: int = 2
ENTITY_REFERENCE_NODE: int = 5
ENTITY_NODE: int = 6
NOTATION_NODE: int = 12
parentNode: Node | None
prefix: str | None
outerText: Any
property content
stream()[source]

Yield rendered HTML chunks without materialising the full subtree.

Return type:

Iterator[str]

property assignedSlot
appendChild(aChild)[source]

Adds a child to the current element. If aChild is a DocumentFragment, all its children are added.

Parameters:

aChild (Node) – The Node to add.

Return type:

Node

property childElementCount: int

Returns the number of child elements an element has

property childNodes: NodeList

Returns a live NodeList containing all the children of this node

property children: list[Node]

Returns a live collection of child nodes, excluding string content.

compareDocumentPosition(otherElement)[source]

A bitmask of DOCUMENT_POSITION_* flags describing where otherElement sits relative to this node (https://dom.spec.whatwg.org/#dom-node-comparedocumentposition).

The spec’s combined masks are returned: an ancestor is CONTAINS | PRECEDING (10), a descendant is CONTAINED_BY | FOLLOWING (20), and two nodes in different trees are DISCONNECTED | IMPLEMENTATION_SPECIFIC | (PRECEDING or FOLLOWING) with the direction stable and anticommutative for a given pair.

Return type:

int

contains(node)[source]

Check whether a node is a descendant of a given node

Return type:

bool

property firstChild: Node | None

Returns the first child node of an element

hasChildNodes()[source]

Returns true if an element has any child nodes, otherwise false

Return type:

bool

property lastChild: Node | None

Returns the last child node of an element

property localName: str | None
property nodeName: str | None

Returns the name of a node

nodeType: int = 1
property nodeValue: str | None

Sets or returns the value of a node

property baseURI: str

Returns the absolute base URL for this node.

property parentElement: Node | None

This node’s parent, but only if that parent is an element – a Document or DocumentFragment parent yields None (https://dom.spec.whatwg.org/#dom-node-parentelement).

property ownerDocument: Node | None

Returns the root element (document object) for an element

property rootNode: Node

Read-only property returning a Node object representing the topmost node in the tree, or the current node if it’s the topmost node in the tree.

Returns:

The topmost Node in the tree.

Return type:

Node

insertBefore(new_node, reference_node=None)[source]

inserts a node before a reference node as a child of a specified parent node. this will remove the node from its previous parent node, if any.

Return type:

Node

removeChild(node)[source]

removes a child node from the DOM and returns the removed node.

Return type:

Any

replaceChild(newChild, oldChild)[source]

Replaces a child node within the given (parent) node.

Parameters:
  • newChild (Node) – The replacement Node.

  • oldChild (Node) – The Node to be replaced.

Returns:

The old child node.

Return type:

Node

cloneNode(deep=True)[source]

Returns a copy.

isSameNode(node)[source]

Checks if two elements are the same node

isEqualNode(node)[source]

Whether node is equal to this one – same type, the same interface-specific fields, an equal (unordered) attribute set, and recursively equal children in order (https://dom.spec.whatwg.org/#concept-node-equals). Not the same as == / isSameNode (identity).

Return type:

bool

getRootNode(options=None)[source]
isDefaultNamespace(ns)[source]

https://dom.spec.whatwg.org/#dom-node-isdefaultnamespace

Compares against the namespace in scope at this node (what lookupNamespaceURI(None) resolves to) – not this node’s own namespaceURI, which is a different question (e.g. every node defaults to the HTML namespace at construction, including a DocumentFragment, which should never report itself as being in it).

lookupNamespaceURI(ns)[source]

Returns the namespace URI for a given prefix

Parameters:

ns (str) – prefix - i.e ‘xml’, ‘xlink’, ‘svg’, etc

lookupPrefix(ns)[source]

Returns the prefix for a given namespace URI

property nextSibling

returns the next sibling of the current node.

normalize()[source]

Normalize a node’s value

property previousSibling

returns the previous sibling of the current node.

property textContent

Returns the text content of a node and its descendants

iter(tag=None)[source]

Creates a tree iterator with the current element as the root. The iterator iterates over this element and all elements below it, in document (depth first) order. If tag is not None or ‘*’, only elements whose tag equals tag are returned from the iterator. If the tree structure is modified during iteration, the result is undefined.

property tag

Returns the tag name of the current node.

ElementTree / elementpath compatibility – always the lower-case local name for an element (tagName upper-cases for an HTML document, which etree-style code does not expect), else nodeName.

property text

Returns the text content of the current node

property attrib

Returns the attributes of the current node as a dict not a NamedNodeMap

property tail

text that follows this element’s end tag.

domonic models trailing text as a sibling text node rather than an attribute of the preceding element, so there is nothing to return here. (Returning the subtree text made every elementpath tree build walk the whole subtree twice per node.)

Type:

ElementTree compatibility

property length: int
is_matching(name, default_namespace=None)[source]

Determine if this node matches the given name and namespace.

append(*items)
Return type:

Any

clear()
property contents: list[Any]
decode(*args, **kwargs)

Beautiful Soup’s .decode() - the string form of the tree.

Return type:

str

decompose()
property descendants: Iterator[Any]
encode(encoding='utf-8', *args, **kwargs)

Beautiful Soup’s .encode() - the byte form of the tree.

Return type:

bytes

extend(items)
extract()
Return type:

Node

find(name=None, attrs=None, recursive=True, string=None, **kwargs)
Return type:

Any | None

findAll(name=None, attrs=None, recursive=True, string=None, limit=None, **kwargs)
Return type:

list[Any]

findAllNext(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findAllPrevious(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findChild(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findChildren(name=None, attrs=None, limit=None, string=None, **kwargs)
Return type:

list[Any]

findNext(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findNextSibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findNextSiblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findParent(name=None, attrs=None, **kwargs)
Return type:

Any | None

findParents(name=None, attrs=None, limit=None, **kwargs)
Return type:

list[Any]

findPrevious(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findPreviousSibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findPreviousSiblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all(name=None, attrs=None, recursive=True, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all_next(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all_previous(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_child(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_children(name=None, attrs=None, limit=None, string=None, **kwargs)
Return type:

list[Any]

find_next(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_next_sibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_next_siblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_parent(name=None, attrs=None, **kwargs)
Return type:

Any | None

find_parents(name=None, attrs=None, limit=None, **kwargs)
Return type:

list[Any]

find_previous(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_previous_sibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_previous_siblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

getText(separator='', strip=False, types=None)
Return type:

str

get_text(separator='', strip=False, types=None)
Return type:

str

insert(index, item)
Return type:

Any

insert_after(item)
Return type:

Any

insert_before(item)
Return type:

Any

new_string(value='')
Return type:

Text

new_tag(name, namespace=None, nsprefix=None, attrs=None, **kwargs)
Return type:

Element

property next_element: Any | None
property next_elements: Iterator[Any]
property next_sibling: Any | None
property next_siblings: Iterator[Any]
property parent: Node | None
property parents: Iterator[Node]
prettify(formatter='minimal', indent=' ')

Beautiful Soup’s prettify() – one node per line, indent per level.

Linear in the document size (the old implementation went through Node.__format__, which recomputed each node’s depth by walking its parent chain – O(n * depth)).

Return type:

str

property previous_element: Any | None
property previous_elements: Iterator[Any]
property previous_sibling: Any | None
property previous_siblings: Iterator[Any]
replace_with(*nodes)
Return type:

Node

select(selector, limit=None, **kwargs)
Return type:

list[Element]

select_one(selector, **kwargs)
Return type:

Element | None

smooth()
property string: str | Text | None
property strings: Iterator[str]
property stripped_strings: Iterator[str]
unwrap()
Return type:

Node

wrap(wrapper)
Return type:

Element

class domonic.dom.ParentNode(*args, **kwargs)[source]

Bases: object

property children: NodeList

Return list of child nodes.

property firstElementChild

First Element child node.

property lastElementChild

Last Element child node.

append(*args)[source]
prepend(*args)[source]
replaceChildren(*children)[source]
class domonic.dom.ChildNode(*args, **kwargs)[source]

Bases: Node

remove()[source]

Removes this ChildNode from the children list of its parent.

replaceWith(*nodes)[source]

Replaces this ChildNode with one or more nodes or strings.

before(*nodes)[source]

Inserts one or more nodes or strings immediately before this ChildNode.

after(*nodes)[source]

Inserts one or more nodes or strings immediately after this ChildNode.

class domonic.dom.Attr(name, value='', *args, **kwargs)[source]

Bases: Node

nodeType: int = 2
name: str
value
parentNode: Element | None
property ownerElement: Element | None

//dom.spec.whatwg.org/#dom-attr-ownerelement – the element this attribute is attached to (via setAttributeNode et al), or None for a detached Attr made with document.createAttribute().

Type:

https

property localName: str
property prefix: str | None
property namespaceURI: str | None
property specified: bool

Legacy attribute the spec keeps only for compatibility – it always returns True (https://dom.spec.whatwg.org/#dom-attr-specified).

property isId: bool
getNamedItem(name)[source]

Returns a specified attribute node from a NamedNodeMap

removeNamedItem(name)[source]

Removes a specified attribute node

Return type:

bool

setNamedItem(name, value)[source]

Sets the specified attribute node (by name)

Return type:

bool

class domonic.dom.NamedNodeMap(args=None, ownerDocument=None, parentNode=None)[source]

Bases: object

Live attribute collection exposed by Element.attributes.

NamedNodeMap behaves like the DOM interface rather than a plain Python dict: it is ordered, can be accessed by index or attribute name, and stays in sync with the owning element’s current attributes.

property length: int
item(index)[source]
Return type:

Attr | None

getNamedItem(name)[source]
Return type:

Attr | None

setNamedItem(attr)[source]
Return type:

Attr | None

removeNamedItem(name)[source]
Return type:

Attr | None

getNamedItemNS(namespaceURI, localName)[source]
Return type:

Attr | None

setNamedItemNS(attr)[source]
Return type:

Attr | None

removeNamedItemNS(namespaceURI, localName)[source]
Return type:

Attr | None

keys()[source]
Return type:

list[str]

values()[source]
Return type:

list[Attr]

items()[source]
Return type:

list[tuple[str, Attr]]

class domonic.dom.DOMStringMap(*args, element=None, **kwargs)[source]

Bases: object

Dictionary-like helper for element dataset values.

keys()[source]
values()[source]
items()[source]
get(name)[source]

Returns the value of the item with the specified name

set(name, value)[source]

Sets the value of the item with the specified name

delete(name)[source]

Deletes the item with the specified name

Return type:

bool

class domonic.dom.DOMRectReadOnly(x=0, y=0, width=0, height=0)[source]

Bases: object

Read-only rectangle object for DOM geometry APIs.

static fromRect(other=None)[source]
Return type:

DOMRectReadOnly

property x: float
property y: float
property width: float
property height: float
property top: float
property right: float
property bottom: float
property left: float
toJSON()[source]
class domonic.dom.DOMRect(x=0, y=0, width=0, height=0)[source]

Bases: DOMRectReadOnly

Mutable rectangle object for DOM geometry APIs.

static fromRect(other=None)[source]
Return type:

DOMRect

property x: float
property y: float
property width: float
property height: float
class domonic.dom.DOMRectList(iterable=(), /)[source]

Bases: list

An ordered collection of DOMRect objects.

property length: int
item(index)[source]
Return type:

DOMRect | None

class domonic.dom.DocumentTimeline(document=None, originTime=0.0)[source]

Bases: object

Document-associated timeline used by animation surfaces.

This is the timing source behind document.timeline and Element.animate(...).

property currentTime: float

Milliseconds on the same clock as performance.now(), offset by originTime (https://drafts.csswg.org/web-animations-1/#document-timelines).

class domonic.dom.CaretPosition(offsetNode=None, offset=0)[source]

Bases: object

Represents a caret location as a node plus offset pair.

getClientRect()[source]
Return type:

DOMRect

class domonic.dom.Selection[source]

Bases: object

Represents the user’s current selection within a document or shadow tree.

Domonic keeps both ordered Range data and anchor/focus information so selection direction can still be represented.

property rangeCount: int
property isCollapsed: bool
property anchorNode: Node | None
property anchorOffset: int
property focusNode: Node | None
property focusOffset: int
property type: str
addRange(range_obj)[source]
removeRange(range_obj)[source]
removeAllRanges()[source]
getRangeAt(index)[source]
Return type:

Range

collapse(node, offset=0)[source]
collapseToStart()[source]
collapseToEnd()[source]
extend(node, offset=0)[source]
setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset)[source]
empty()[source]
selectAllChildren(node)[source]
deleteFromDocument()[source]
containsNode(node, allowPartialContainment=False)[source]
Return type:

bool

toString()[source]
Return type:

str

class domonic.dom.DOMTokenList(element)[source]

Bases: list

DOMTokenList represents a set of space-separated tokens.

property length: int
property value: str
add(*args)[source]

Adds the given tokens to the list

remove(*args)[source]

Removes the given tokens from the list

toggle(token, force=None)[source]

If force is not given, removes token from list if present, otherwise adds token to list. If force is true, adds token to list, and if force is false, removes token from list if present.

A force toggle that is a no-op (adding a token already present, or removing one that is absent) does not run the update steps – the class attribute is left byte-for-byte unchanged (DOM spec).

replace(token, newToken)[source]

Replaces token with newToken, in place, then drops any other occurrence of newToken (https://dom.spec.whatwg.org/#dom-domtokenlist-replace).

Per spec the empty-string check for both arguments happens before the whitespace check for either, so replace(" ", "") is a SyntaxError (empty newToken), not an InvalidCharacterError.

Return type:

bool

contains(token)[source]

Returns true if the token is in the list, and false otherwise.

Does not validate token – an empty string or one containing whitespace simply is not present, so this returns False (DOM spec; only the mutating methods throw).

Return type:

bool

supports(token)[source]

A classList has no defined set of supported tokens, so per the DOM spec supports() always throws TypeError.

Return type:

bool

item(index)[source]

Returns the token at the specified index, or None if out of range.

toString()[source]

The stringifier returns the associated attribute’s value verbatim – it is not normalised (DOM spec: the stringifier is the class attribute’s value, so "  a  a b" stringifies to "  a  a b").

Return type:

str

entries()[source]

Returns an iterator over index/token pairs.

Return type:

Iterable[tuple[int, str]]

forEach(func, thisArg=None)[source]

Calls a function for each token in the list.

keys()[source]

Returns an iterator over token indexes.

Return type:

Iterable[int]

values()[source]

Returns an iterator over tokens.

Return type:

Iterable[str]

class domonic.dom.ShadowRoot(host, mode='open')[source]

Bases: Node

property on element that has hidden DOM

elementFromPoint(x, y)[source]

Returns the topmost element at the specified coordinates.

Return type:

Element | None

getSelection()[source]

Returns a Selection object for the document.

Return type:

Selection

elementsFromPoint(x, y)[source]

Returns an array of all elements at the specified coordinates.

Return type:

list[Element]

caretPositionFromPoint(x=0, y=0)[source]

Returns a CaretPosition object containing the DOM node containing the caret, and caret’s character offset within that node.

Return type:

CaretPosition | None

class domonic.dom.DocumentType(name='html', publicId='', systemId='')[source]

Bases: Node

nodeType: int = 10
name: str
publicId: str
systemId: str
property internalSubset

A DOMString of the internal subset, or None. Eg “<!ELEMENT foo (bar)>”.

property entities: NamedNodeMap

A NamedNodeMap with entities declared in the DTD.

property notations: NamedNodeMap

A NamedNodeMap with notations declared in the DTD.

stream()[source]

Yield rendered HTML chunks without materialising the full subtree.

Return type:

Iterator[str]

class domonic.dom.CustomStateSet(states=None)[source]

Bases: object

Set-like storage for custom element states.

property size: int
add(state)[source]
Return type:

CustomStateSet

clear()[source]
delete(state)[source]
Return type:

bool

entries()[source]
Return type:

Iterator[tuple[str, str]]

forEach(callback, thisArg=None)[source]
has(state)[source]
Return type:

bool

keys()[source]
Return type:

Iterator[str]

values()[source]
Return type:

Iterator[str]

class domonic.dom.NodeList(iterable=(), /)[source]

Bases: list

NodeList objects are collections of nodes

property length: int
item(index)[source]

Returns an item in the list by its index, or null if the index is out-of-bounds.

Return type:

Node | None

entries()[source]

Returns an iterator, allowing code to go through all key/value pairs contained in the collection. (In this case, the keys are numbers starting from 0 and the values are nodes.

Return type:

Iterable[tuple[int, Node]]

forEach(func, thisArg=None)[source]

Calls a function for each item in the NodeList.

keys()[source]

Returns an iterator, allowing code to go through all the keys of the key/value pairs contained in the collection. (In this case, the keys are numbers starting from 0.)

Return type:

Iterable[int]

values()[source]

Returns an iterator allowing code to go through all values (nodes) of the key/value pairs contained in the collection.

Return type:

Iterable[Node]

class domonic.dom.RadioNodeList(nodes=None, name=None, owner=None)[source]

Bases: NodeList

A live collection of form controls sharing an id or name.

name: str
property length: int
property value: Any

Returns the value of the first element in the collection, or null if there are no elements in the collection.

class domonic.dom.Element(*args, **kwargs)[source]

Bases: Node

Baseclass for all html tags

property childElementCount: int

Returns the number of child elements an element has.

property children: list[Node]

Returns child elements, excluding text, comments, and strings.

matches(s)[source]

Checks to see if the Element would be selected by the provided selectorString.

https://developer.mozilla.org/en-US/docs/Web/API/Element/matches

Parameters:

s (str) – A CSS selector string.

Returns:

True if the selector matches the Element, otherwise False.

Return type:

bool

webkitMatchesSelector(s)

Checks to see if the Element would be selected by the provided selectorString.

https://developer.mozilla.org/en-US/docs/Web/API/Element/matches

Parameters:

s (str) – A CSS selector string.

Returns:

True if the selector matches the Element, otherwise False.

Return type:

bool

closest(s)[source]
getElementsBySelector(all_selectors, document)[source]

Get DOM elements based on the given CSS Selector.

Original sources: - https://simonwillison.net/2003/Mar/25/getElementsBySelector/ - http://www.openjs.com/scripts/dom/css_selector/ - https://bin-co.com/python/scripts/getelementsbyselector-html-css-query.php (ported to Python 2, broken/bugs, BSD licensed)

Note: - Preserved as a compatibility helper for older selector-style code. - Supports simple descendant selector chains plus tag, id, class, and attribute selectors.

Parameters:
  • all_selectors (str) – The CSS selectors to query.

  • document (object) – The document object to search within.

Returns:

A list of elements matching the CSS selectors.

Return type:

list

append(*items)
Return type:

Any

attachShadow(obj)[source]
property attributes: NamedNodeMap

Returns a NamedNodeMap of an element’s attributes

property innerHTML

Return this element’s content as an HTML-fragment-serialised string.

Matches a browser’s innerHTML getter (WHATWG fragment serialisation: <br> not <br/>, checked="" not bare checked, only & " \xa0 escaped in attribute values). str(node) keeps domonic’s XHTML-style authoring output.

property outerHTML

Return this element serialised per the HTML fragment algorithm.

Browser-compatible counterpart to str(self) – see innerHTML.

getHTML(options=None)[source]

DOM Element.getHTML() – serialised inner HTML.

options is accepted for signature compatibility; shadow-root serialisation is not implemented.

Return type:

str

html(*args)[source]
setHTML(input, options=None)[source]

Replace children with sanitized HTML.

Mirrors the browser Element.setHTML() method. It always applies unsafe-element and unsafe-attribute removal before inserting the resulting fragment.

setHTMLUnsafe(input, options=None)[source]

Replace children from HTML, optionally using a Sanitizer config.

blur()[source]

Removes focus from an element

property classList

Returns the value of the classList attribute of an element

property className

The element’s class content attribute reflected as a string – "" when absent (IDL string reflection, never None).

click()[source]

Simulates a mouse-click on an element

animate(keyframes, options=None)[source]
property clientHeight

Returns the height of an element, including padding

property clientLeft

Returns the width of the left border of an element

property clientTop

Returns the width of the top border of an element

property clientWidth

Returns the width of an element, including padding

property contentEditable: bool

Sets or returns whether an element is editable

property dataset

Returns the value of the dataset attribute of an element

property dir

returns the value of the dir attribute of an element

exitFullscreen()[source]

Cancels an element in fullscreen mode

property firstElementChild

Returns the first child element of an element

focus()[source]

Sets focus on an element

setAttributeNodeNS(attr)[source]

Sets the attribute node of an element

getAttributeNodeNS(attr)[source]

Sets the attribute node of an element

setAttributeNS(namespaceURI, localName, value)[source]

Sets an attribute in the given namespace

getAttributeNS(namespaceURI, localName)[source]

Returns the value of the specified attribute

hasAttributeNS(namespaceURI, localName)[source]

Whether the element has the given attribute.

domonic does not track per-attribute namespaces (see the domonic-wpt-conformance notes), so the namespace argument is ignored and this is equivalent to hasAttribute(localName).

Return type:

bool

removeAttributeNS(namespaceURI, localName)[source]

Removes an attribute from an element

getAttributeNames()[source]

The qualified names of this element’s attributes, in order.

Return type:

list[str]

getAttribute(attribute)[source]

Returns the specified attribute value of an element node

Return type:

str

getAttributeNode(attribute)[source]

Returns the specified attribute node

Return type:

Attr | None

set_layout_box(box)[source]

Attach the box a layout engine computed for this element.

Once set, getBoundingClientRect/clientWidth/clientHeight/ clientTop/clientLeft/offsetWidth/offsetHeight/ offsetLeft/offsetTop report it instead of falling back to their inline-style heuristic. See domonic.layout.LayoutBox.

get_layout_box()[source]

The domonic.layout.LayoutBox last set on this element, or None if no layout engine has supplied one yet.

getBoundingClientRect()[source]

Returns the size of an element and its position relative to the viewport

measureText(text=None)[source]

(width, height, ascent, descent) in px for text (this element’s own textContent by default) set in this element’s computed font-size/font-weight.

The same bundled font metrics table getComputedTextLength() uses for SVG <text>, but exposed for any element – getBBox() stays SVG-only per spec (a real browser doesn’t have it on plain HTML), so this is the public, HTML-facing way to get real text measurements (e.g. for a layout engine adapter sizing a text leaf) without reaching into domonic._fontmetrics directly.

Return type:

tuple[float, float, float, float]

getBBox()[source]

The tight geometry box of this element in its own user space.

Works for any SVG-namespaced element or SVG-named tag: leaf shapes use their attributes, <text> / <tspan> are measured with the bundled font metrics (via the computed font-size / font-weight), and containers such as <g> return the union of their rendered descendants with each child’s transform applied.

Return type:

DOMRect

getComputedTextLength()[source]

Advance width of this text element’s content, in user units.

Return type:

float

getSubStringLength(charnum=0, nchars=None)[source]
Return type:

float

getNumberOfChars()[source]
Return type:

int

getCTM()[source]

Transform from this element’s user space to its nearest viewport.

Return type:

DOMMatrix

getScreenCTM()[source]

Transform from this element’s user space to the document root.

Return type:

DOMMatrix

getTransformToElement(element)[source]
Return type:

DOMMatrix

createSVGPoint(x=0.0, y=0.0)[source]
Return type:

DOMPoint

createSVGRect()[source]
Return type:

DOMRect

createSVGMatrix()[source]
Return type:

DOMMatrix

getSelection()[source]

Returns a Selection object for this element’s root tree.

getElementsByClassName(className)[source]

Returns a collection of all child elements with the specified class name.

Parameters:

className (str) – A DOMString representing the class name to match.

Returns:

All child elements with the specified class name.

Return type:

HTMLCollection

getElementById(_id)[source]

Returns the descendant element whose id matches the supplied value.

Backed by a lazily-built id -> element index that is rebuilt only after a DOM mutation, so repeated lookups on a static tree are O(1).

Return type:

Element | None

elementFromPoint(x, y)[source]

Returns the topmost element in this subtree at the specified coordinates.

Return type:

Element | None

elementsFromPoint(x, y)[source]

Returns all elements in this subtree at the specified coordinates.

Return type:

list[Element]

caretPositionFromPoint(x, y)[source]

Returns a CaretPosition for the closest element within this subtree.

Return type:

CaretPosition | None

getElementsByTagName(tagName)[source]

Returns a collection of all child elements with the specified tag name.

Parameters:

tagName (str) – A DOMString representing the tag name to match.

Returns:

A live HTMLCollection of elements with the given tag name.

Return type:

HTMLCollection

hasAttribute(attribute)[source]

Returns True if an element has the specified attribute, otherwise False.

Parameters:

attribute (str) – The attribute to test for.

Returns:

True if an element has the specified attribute, otherwise False.

Return type:

bool

hasAttributes()[source]

Returns true if an element has any attributes, otherwise false

Return type:

bool

property hidden: bool

Reflects the boolean hidden content attribute.

property tabIndex: int

Reflects tabindex as an integer; -1 when absent or invalid.

property id: str

The element’s id content attribute reflected as a string – "" when the attribute is absent (IDL string reflection, never None).

innerText(*args)[source]
Return type:

str

before(*nodes)[source]

ChildNode.before – insert nodes as previous siblings.

after(*nodes)[source]

ChildNode.after – insert nodes as next siblings.

replaceWith(*nodes)[source]

ChildNode.replaceWith – replace this element with nodes (strings included; this element itself may appear among them).

insertAdjacentElement(position, element)[source]

Inserts an element adjacent to the current element.

Return type:

Element | None

insertAdjacentHTML(position, html)[source]

Inserts raw HTML adjacent to the current element

insertAdjacentText(position, text)[source]

Inserts text adjacent to the current element

isContentEditable()[source]

Returns true if the content of an element is editable, otherwise false

Return type:

bool

property lang: str | None

Sets or returns the value of the lang attribute of an element.

property lastElementChild: Node | None

Returns the last child element of an element.

Returns:

The last child element of an element.

Return type:

Element | None

property nextSibling: Node | None

Returns the next node at the same node tree level

property nextElementSibling: Node | None

Returns the next element at the same node tree level

property previousElementSibling: Node | None

returns the Element immediately prior to the specified one in its parent’s children list, or None if the specified element is the first one in the list.

normalize()[source]

Joins adjacent text nodes and removes empty text nodes in an element

Return type:

tuple[Any, …]

offsetHeight()[source]

Returns the height of an element, including padding, border and scrollbar

Return type:

float

offsetWidth()[source]

Returns the width of an element, including padding, border and scrollbar

Return type:

float

offsetLeft()[source]

Returns the horizontal offset position of an element

Return type:

float

offsetParent()[source]

Returns the offset container of an element

Return type:

Node | None

offsetTop()[source]

Returns the vertical offset position of an element

Return type:

float

prepend(*args)[source]

Prepends a node to the current element

replaceChildren(*nodes)[source]

Replaces the element’s children with the supplied nodes.

querySelector(query)[source]

Returns the first child element that matches a specified CSS selector(s) of an element.

Parameters:

query (str) – A CSS selector string.

Returns:

The first matching Element, or None.

Return type:

Element | None

querySelectorAll(query)[source]

Returns all child elements that match a specified CSS selector(s) of an element.

Parameters:

query (str) – A CSS selector string.

Returns:

A list of matching Element objects.

Return type:

list[Element]

remove()[source]

Removes the element from the DOM

removeAttribute(attribute)[source]

Removes a specified attribute from an element

removeAttributeNode(attribute)[source]

Removes a specified attribute node, and returns the removed node

requestFullscreen()[source]

Shows an element in fullscreen mode

scrollHeight()[source]

Returns the entire height of an element, including padding

scrollIntoView()[source]

Scrolls the specified element into the visible area of the browser window

scrollLeft()[source]

Sets or returns the number of pixels an element’s content is scrolled horizontally

scrollTop()[source]

Sets or returns the number of pixels an element’s content is scrolled vertically

scrollWidth()[source]

Returns the entire width of an element, including padding

setAttribute(attribute, value)[source]

Sets or changes the specified attribute, to the specified value

toggleAttribute(attribute, force=None)[source]

Adds or removes an attribute and returns whether it is present afterwards.

A force call that is a no-op (forcing on an attribute that is already set, or off one that is absent) does not touch the attribute – in particular it does not blank an existing value (DOM spec).

Return type:

bool

setAttributeNode(attr)[source]

Sets or changes the specified attribute node.

Parameters:

attr (Attr) – An Attr object.

property style

returns the value of the style attribute of an element

property attributeStyleMap

CSS Typed OM view over the inline style declaration block.

computedStyleMap()[source]

CSS Typed OM read-only view over the element’s computed style.

property tagName
property title

returns the value of the title attribute of an element

toString()[source]

Converts an element to a string

Return type:

str

property ariaActiveDescendantElement

Reflects the aria-activedescendant ID reference.

property ariaAtomic

Reflects the aria-atomic attribute.

property ariaAutoComplete

Reflects the aria-autocomplete attribute.

property ariaBrailleLabel

Reflects the aria-braillelabel attribute.

property ariaBrailleRoleDescription

Reflects the aria-brailleroledescription attribute.

property ariaBusy

Reflects the aria-busy attribute.

property ariaChecked

Reflects the aria-checked attribute.

property ariaColCount

Reflects the aria-colcount attribute.

property ariaColIndex

Reflects the aria-colindex attribute.

property ariaColIndexText

Reflects the aria-colindextext attribute.

property ariaColSpan

Reflects the aria-colspan attribute.

property ariaControlsElements

Reflects the aria-controls ID reference.

property ariaCurrent

Reflects the aria-current attribute.

property ariaDescribedByElements

Reflects the aria-describedby ID reference.

property ariaDescription

Reflects the aria-description attribute.

property ariaDetailsElements

Reflects the aria-details ID reference.

property ariaDisabled

Reflects the aria-disabled attribute.

property ariaErrorMessageElements

Reflects the aria-errormessage ID reference.

property ariaExpanded

Reflects the aria-expanded attribute.

property ariaFlowToElements

Reflects the aria-flowto ID reference.

property ariaHasPopup

Reflects the aria-haspopup attribute.

property ariaHidden

Reflects the aria-hidden attribute.

property ariaInvalid

Reflects the aria-invalid attribute.

property ariaKeyShortcuts

Reflects the aria-keyshortcuts attribute.

property ariaLabel

Reflects the aria-label attribute.

property ariaLabelledByElements

Reflects the aria-labelledby ID reference.

property ariaLevel

Reflects the aria-level attribute.

property ariaLive

Reflects the aria-live attribute.

property ariaModal

Reflects the aria-modal attribute.

property ariaMultiLine

Reflects the aria-multiline attribute.

property ariaMultiSelectable

Reflects the aria-multiselectable attribute.

property ariaOrientation

Reflects the aria-orientation attribute.

property ariaOwnsElements

Reflects the aria-owns ID reference.

property ariaPlaceholder

Reflects the aria-placeholder attribute.

property ariaPosInSet

Reflects the aria-posinset attribute.

property ariaPressed

Reflects the aria-pressed attribute.

property ariaReadOnly

Reflects the aria-readonly attribute.

property ariaRelevant

Reflects the aria-relevant attribute.

property ariaRequired

Reflects the aria-required attribute.

property ariaRoleDescription

Reflects the aria-roledescription attribute.

property ariaRowCount

Reflects the aria-rowcount attribute.

property ariaRowIndex

Reflects the aria-rowindex attribute.

property ariaRowIndexText

Reflects the aria-rowindextext attribute.

property ariaRowSpan

Reflects the aria-rowspan attribute.

property ariaSelected

Reflects the aria-selected attribute.

property ariaSetSize

Reflects the aria-setsize attribute.

property ariaSort

Reflects the aria-sort attribute.

property ariaValueMax

Reflects the aria-valuemax attribute.

property ariaValueMin

Reflects the aria-valuemin attribute.

property ariaValueNow

Reflects the aria-valuenow attribute.

property ariaValueText

Reflects the aria-valuetext attribute.

property attrs: dict[str, Any]
clear()
property contents: list[Any]
decode(*args, **kwargs)

Beautiful Soup’s .decode() - the string form of the tree.

Return type:

str

decompose()
property descendants: Iterator[Any]
encode(encoding='utf-8', *args, **kwargs)

Beautiful Soup’s .encode() - the byte form of the tree.

Return type:

bytes

extend(items)
extract()
Return type:

Node

find(name=None, attrs=None, recursive=True, string=None, **kwargs)
Return type:

Any | None

findAll(name=None, attrs=None, recursive=True, string=None, limit=None, **kwargs)
Return type:

list[Any]

findAllNext(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findAllPrevious(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findChild(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findChildren(name=None, attrs=None, limit=None, string=None, **kwargs)
Return type:

list[Any]

findNext(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findNextSibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findNextSiblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findParent(name=None, attrs=None, **kwargs)
Return type:

Any | None

findParents(name=None, attrs=None, limit=None, **kwargs)
Return type:

list[Any]

findPrevious(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findPreviousSibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findPreviousSiblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all(name=None, attrs=None, recursive=True, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all_next(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all_previous(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_child(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_children(name=None, attrs=None, limit=None, string=None, **kwargs)
Return type:

list[Any]

find_next(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_next_sibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_next_siblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_parent(name=None, attrs=None, **kwargs)
Return type:

Any | None

find_parents(name=None, attrs=None, limit=None, **kwargs)
Return type:

list[Any]

find_previous(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_previous_sibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_previous_siblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

get(key, default=None)
Return type:

Any

getText(separator='', strip=False, types=None)
Return type:

str

get_text(separator='', strip=False, types=None)
Return type:

str

has_attr(key)
Return type:

bool

has_key(key)
Return type:

bool

insert(index, item)
Return type:

Any

insert_after(item)
Return type:

Any

insert_before(item)
Return type:

Any

new_string(value='')
Return type:

Text

new_tag(name, namespace=None, nsprefix=None, attrs=None, **kwargs)
Return type:

Element

property next_element: Any | None
property next_elements: Iterator[Any]
property next_sibling: Any | None
property next_siblings: Iterator[Any]
property parent: Node | None
property parents: Iterator[Node]
prettify(formatter='minimal', indent=' ')

Beautiful Soup’s prettify() – one node per line, indent per level.

Linear in the document size (the old implementation went through Node.__format__, which recomputed each node’s depth by walking its parent chain – O(n * depth)).

Return type:

str

property previous_element: Any | None
property previous_elements: Iterator[Any]
property previous_sibling: Any | None
property previous_siblings: Iterator[Any]
replace_with(*nodes)
Return type:

Node

property role

Reflects the role attribute.

select(selector, limit=None, **kwargs)
Return type:

list[Element]

select_one(selector, **kwargs)
Return type:

Element | None

smooth()
property string: str | Text | None
property strings: Iterator[str]
property stripped_strings: Iterator[str]
unwrap()
Return type:

Node

wrap(wrapper)
Return type:

Element

class domonic.dom.DOMImplementation[source]

Bases: object

createDocument(namespaceURI, qualifiedName, doctype)[source]
createDocumentType(qualifiedName, publicId, systemId)[source]

Creates a DocumentType node.

Parameters:
  • qualifiedName (str) – The qualified name of the document type.

  • publicId (str) – The public identifier of the document type.

  • systemId (str) – The system identifier of the document type.

Returns:

A DocumentType object.

Return type:

DocumentType

createHTMLDocument(title=None)[source]
hasFeatures(featureList)[source]
Return type:

bool

hasFeature(feature=None, version=None)[source]

Return whether a DOM feature is supported.

Modern DOM implementations keep this method for compatibility and report support for all feature strings.

Return type:

bool

class domonic.dom.ProcessingInstruction(target, data)[source]

Bases: _CharacterDataOnAttr, ChildNode

nodeType: int = 7
target
property nodeValue: str

Sets or returns the value of a node

property textContent: str

Returns the text content of a node and its descendants

toString()[source]
Return type:

str

stream()[source]

Yield rendered HTML chunks without materialising the full subtree.

Return type:

Iterator[str]

class domonic.dom.Comment(*data)[source]

Bases: _CharacterDataOnAttr, ChildNode

nodeType: int = 8
nodeName: str = '#comment'
property nodeValue: str

Sets or returns the value of a node

property textContent: str

Returns the text content of a node and its descendants

toString()[source]
Return type:

str

stream()[source]

Yield rendered HTML chunks without materialising the full subtree.

Return type:

Iterator[str]

property length: int
append(*items)
Return type:

Any

clear()
property contents: list[Any]
decode(*args, **kwargs)

Beautiful Soup’s .decode() - the string form of the tree.

Return type:

str

decompose()
property descendants: Iterator[Any]
encode(encoding='utf-8', *args, **kwargs)

Beautiful Soup’s .encode() - the byte form of the tree.

Return type:

bytes

extend(items)
extract()
Return type:

Node

find(name=None, attrs=None, recursive=True, string=None, **kwargs)
Return type:

Any | None

findAll(name=None, attrs=None, recursive=True, string=None, limit=None, **kwargs)
Return type:

list[Any]

findAllNext(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findAllPrevious(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findChild(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findChildren(name=None, attrs=None, limit=None, string=None, **kwargs)
Return type:

list[Any]

findNext(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findNextSibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findNextSiblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findParent(name=None, attrs=None, **kwargs)
Return type:

Any | None

findParents(name=None, attrs=None, limit=None, **kwargs)
Return type:

list[Any]

findPrevious(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findPreviousSibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findPreviousSiblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all(name=None, attrs=None, recursive=True, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all_next(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all_previous(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_child(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_children(name=None, attrs=None, limit=None, string=None, **kwargs)
Return type:

list[Any]

find_next(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_next_sibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_next_siblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_parent(name=None, attrs=None, **kwargs)
Return type:

Any | None

find_parents(name=None, attrs=None, limit=None, **kwargs)
Return type:

list[Any]

find_previous(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_previous_sibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_previous_siblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

getText(separator='', strip=False, types=None)
Return type:

str

get_text(separator='', strip=False, types=None)
Return type:

str

insert(index, item)
Return type:

Any

insert_after(item)
Return type:

Any

insert_before(item)
Return type:

Any

new_string(value='')
Return type:

Text

new_tag(name, namespace=None, nsprefix=None, attrs=None, **kwargs)
Return type:

Element

property next_element: Any | None
property next_elements: Iterator[Any]
property next_sibling: Any | None
property next_siblings: Iterator[Any]
property parent: Node | None
property parents: Iterator[Node]
prettify(formatter='minimal', indent=' ')

Beautiful Soup’s prettify() – one node per line, indent per level.

Linear in the document size (the old implementation went through Node.__format__, which recomputed each node’s depth by walking its parent chain – O(n * depth)).

Return type:

str

property previous_element: Any | None
property previous_elements: Iterator[Any]
property previous_sibling: Any | None
property previous_siblings: Iterator[Any]
replace_with(*nodes)
Return type:

Node

select(selector, limit=None, **kwargs)
Return type:

list[Element]

select_one(selector, **kwargs)
Return type:

Element | None

smooth()
property string: str | Text | None
property strings: Iterator[str]
property stripped_strings: Iterator[str]
unwrap()
Return type:

Node

wrap(wrapper)
Return type:

Element

class domonic.dom.CDATASection(data)[source]

Bases: _CharacterDataOnAttr, ChildNode

The CDATASection interface represents a CDATA section that can be used within XML to include extended portions of unescaped text, such that the symbols < and & do not need escaping as they normally do within XML when used as text.

nodeType: int = 4
nodeName: str = '#cdata-section'
property nodeValue: str

Sets or returns the value of a node

property textContent: str

Returns the text content of a node and its descendants

toString()[source]
Return type:

str

stream()[source]

Yield rendered HTML chunks without materialising the full subtree.

Return type:

Iterator[str]

property length: int
class domonic.dom.AbastractRange[source]

Bases: object

startContainer: Node | None
startOffset: int
endContainer: Node | None
endOffset: int
collapsed: bool
commonAncestorContainer: Node | None
cloneContents()[source]
Return type:

DocumentFragment

cloneRange()[source]
Return type:

Range

compareBoundaryPoints(how, sourceRange)[source]
Return type:

int

createContextualFragment(data)[source]
Return type:

DocumentFragment

deleteContents()[source]
detach()[source]
expand(unit)[source]
extractContents()[source]
Return type:

DocumentFragment

getBoundingClientRect()[source]
Return type:

DOMRect

getClientRects()[source]
Return type:

DOMRectList

insertNode(newNode)[source]
selectNode(refNode)[source]
selectNodeContents(refNode)[source]
setEnd(refNode, offset)[source]
setEndAfter(refNode)[source]
setEndBefore(refNode)[source]
setStart(refNode, offset)[source]
setStartAfter(refNode)[source]
setStartBefore(refNode)[source]
surroundContents(newParent)[source]
toString()[source]
Return type:

str

comparePoint(refNode, offset)[source]
Return type:

int

deleteData(offset, count)[source]
extractData(offset, count)[source]
getData(offset, count)[source]
getEnd()[source]
getStart()[source]
replaceData(offset, count, data)[source]
setData(data)[source]
domonic.dom.AbstractRange

alias of AbastractRange

class domonic.dom.Range[source]

Bases: AbastractRange

START_TO_START: ClassVar[int] = 0
START_TO_END: ClassVar[int] = 1
END_TO_END: ClassVar[int] = 2
END_TO_START: ClassVar[int] = 3
startContainer: Node | None
endContainer: Node | None
commonAncestorContainer: Node | None
setStart(node, offset)[source]
setEnd(node, offset)[source]
setStartBefore(node)[source]
setStartAfter(node)[source]
setEndBefore(node)[source]
setEndAfter(node)[source]
collapse(toStart=False)[source]
selectNode(node)[source]
selectNodeContents(node)[source]
compareBoundaryPoints(how, sourceRange)[source]
Return type:

int

deleteContents()[source]
extractContents()[source]
Return type:

DocumentFragment

cloneContents()[source]
Return type:

DocumentFragment

getBoundingClientRect()[source]
Return type:

DOMRect

getClientRects()[source]
Return type:

DOMRectList

insertNode(node)[source]
surroundContents(newParent)[source]
cloneRange()[source]
Return type:

Range

detach()[source]

A no-op, kept for legacy compatibility (https://dom.spec.whatwg.org/#dom-range-detach).

createContextualFragment(fragment)[source]
Return type:

DocumentFragment

toString()[source]

https://dom.spec.whatwg.org/#dom-range-stringifier

Concatenates the data of Text node descendants (and, for domonic’s raw-string child shorthand, plain string children) the range spans – not str()/markup of whatever nodes happen to sit between the boundaries. A range spanning <p>hi</p><p>bye</p> stringifies to "hibye", not "<p>hi</p><p>bye</p>".

Return type:

str

comparePoint(refNode, offset)[source]
Return type:

int

isPointInRange(refNode, offset)[source]
Return type:

bool

intersectsNode(refNode)[source]
Return type:

bool

class domonic.dom.StaticRange(startContainer, startOffset, endContainer, endOffset)[source]

Bases: Range

Immutable snapshot of a range boundary pair.

StaticRange mirrors the platform idea of a range-like object that can be inspected and cloned back into a mutable Range but cannot be edited in place.

collapse(*args, **kwargs)
createContextualFragment(fragment)
Return type:

DocumentFragment

deleteContents(*args, **kwargs)
deleteData(*args, **kwargs)
detach(*args, **kwargs)

A no-op, kept for legacy compatibility (https://dom.spec.whatwg.org/#dom-range-detach).

expand(*args, **kwargs)
extractContents(*args, **kwargs)
insertNode(*args, **kwargs)
replaceData(*args, **kwargs)
selectNode(*args, **kwargs)
selectNodeContents(*args, **kwargs)
setData(*args, **kwargs)
setEnd(*args, **kwargs)
setEndAfter(*args, **kwargs)
setEndBefore(*args, **kwargs)
setStart(*args, **kwargs)
setStartAfter(*args, **kwargs)
setStartBefore(*args, **kwargs)
surroundContents(*args, **kwargs)
toRange()[source]
Return type:

Range

class domonic.dom.TimeRanges(*ranges)[source]

Bases: object

start(index)[source]
end(index)[source]
class domonic.dom.Document(*args, **kwargs)[source]

Bases: Element

The Document interface represents the entire HTML or XML document.

URL: str = ''
adoptedStyleSheets: list
property fonts

The document’s CSS Font Loading API FontFaceSet.

adoptNode(node)[source]

Move node (and its subtree) out of its current document and into this one, returning the same node – not a copy (https://dom.spec.whatwg.org/#dom-document-adoptnode).

Return type:

Node

property stylesheets
property styleSheets

DOM-spec spelling of stylesheets.

property activeElement: Element | None

Returns the currently focused element, or the body/document element fallback.

property timeline: DocumentTimeline
property currentScript: Element | None
property defaultView
property designMode: str
hasFocus()[source]

Returns True when the document currently tracks a focused element.

Return type:

bool

property anchors

A live HTMLCollection of the document’s <a name> elements.

property applets

Returns a collection of all <applet> elements in the document

property body

Returns the <body> element in the document

close()[source]

Finish the parse started by open() / write() (https://html.spec.whatwg.org/#dom-document-close): elements still open are closed, readyState moves through "interactive" and "complete", and DOMContentLoaded then load fire.

property cookie: str
property charset

Use characterSet instead.

Type:

Returns the character encoding for the document. Deprecated

property characterSet

The encoding the document was decoded from (https://html.spec.whatwg.org/#dom-document-characterset): what the byte order mark, the transport or the page’s <meta charset> declared when it arrived as bytes, else "UTF-8".

property inputEncoding

Legacy alias of characterSet.

property contentType: str

The document’s MIME type – application/xml for an XMLDocument, text/html otherwise.

property compatMode: str

"CSS1Compat" (standards mode) – domonic never emulates quirks mode, so this is constant.

property readyState: str

A programmatically built or fully parsed document is "complete".

property documentURI: str

Same as URL for a document (the location of the document).

property hidden: bool

Reflects the boolean hidden content attribute.

static createAttribute(name)[source]

Creates an attribute node

Return type:

Attr

static createComment(message)[source]

Creates a Comment node with the specified text

Return type:

Comment

static createDocumentFragment(*args)[source]

Creates an empty DocumentFragment node if not content passed. I added args as optional to pass content

Return type:

DocumentFragment

static parseHTML(input, options=None)[source]

Parse HTML into an HTMLDocument using safe Sanitizer defaults.

Return type:

Document

static parseHTMLUnsafe(input, options=None)[source]

Parse HTML into an HTMLDocument, optionally using a Sanitizer.

Return type:

Document

static createExpression(xpath, nsResolver)[source]

Creates an XPathExpression object for the given XPath string.

Return type:

XPathExpression

static createElement(_type, *args, **kwargs)[source]

Creates an Element node.

The DOM createElement(tagName, options) form is supported for customized built-ins: pass {"is": "my-button"} as a trailing positional dict, or is_= / **{"is": ...} as a keyword.

Return type:

Element

static createElementNS(namespaceURI, qualifiedName, options=None)[source]

Creates an element with the specified namespace URI and qualified name.

Return type:

Element

static createEvent(event_type=None)[source]

Creates a DOM-style event instance for the requested interface.

Parameters:

event_type (str | None) – Event interface name, such as MouseEvent or SubmitEvent. Defaults to a plain Event.

Returns:

A new event object.

Return type:

Event

static createTextNode(text)[source]

Creates a Text node with the specified text.

Parameters:

text (str) – The text to be inserted.

Returns:

A new Text node.

Return type:

Text

static createTreeWalker(root, whatToShow=None, filter=None, entityReferenceExpansion=None)[source]

Creates a TreeWalker object.

Parameters:
  • root (Node) – The root node at which to begin traversal.

  • whatToShow (int, optional) – What types of nodes to show. Defaults to None.

  • filter (Any, optional) – A NodeFilter or a function to be called for each node. Defaults to None.

  • entityReferenceExpansion (Any, optional) – Unused; kept for API compatibility. Defaults to None.

Returns:

A new TreeWalker object.

Return type:

TreeWalker

static createProcessingInstruction(target, data)[source]

Creates a ProcessingInstruction node with the specified target and data.

Per https://dom.spec.whatwg.org/#dom-document-createprocessinginstruction the target must be a valid name and the data must not contain "?>".

Return type:

ProcessingInstruction

static createEntityReference(name)[source]

Creates an EntityReference node with the specified name

Return type:

EntityReference

property xmlversion

Returns the version of XML used for the document

static createCDATASection(data)[source]

Creates a CDATASection node with the specified data

Return type:

CDATASection

createRange()[source]

Creates a Range.

Per the DOM spec a fresh range is anchored at (document, 0) for both boundary points. Called unbound (Document.createRange()) it still returns a bare, unanchored Range for backwards compatibility.

Return type:

Range

static createNodeIterator(root, whatToShow=None, filter=None)[source]

Creates a NodeIterator that can be used to traverse the document tree or subtree under root.

Return type:

NodeIterator

property doctype

Returns the Document Type Declaration associated with the document

domain()[source]

Returns the domain name of the server that loaded the document

domConfig()[source]

Returns the DOMConfig which has settings for how html content is rendered

elementFromPoint(x, y)[source]

Returns the topmost element at the specified coordinates.

Return type:

Element | None

evaluate(xpathExpression, contextNode=None, namespaceResolver=None, resultType=7, result=None)[source]

Evaluates an XPath expression and returns the result.

elementsFromPoint(x, y)[source]

Returns an array of all elements at the specified coordinates.

Return type:

list[Element]

caretPositionFromPoint(x, y)[source]

Returns a CaretPosition for the closest element at the given coordinates.

Return type:

CaretPosition | None

property embeds

A live HTMLCollection of the document’s <embed> elements.

property plugins

A live HTMLCollection of the document’s <embed> elements.

property forms

A live HTMLCollection of the document’s <form> elements.

fullscreenElement()[source]

Returns the current element that is displayed in fullscreen mode

fullscreenEnabled()[source]

Returns a Boolean value indicating whether the document can be viewed in fullscreen mode

getElementById(_id)[source]

Returns the element that has the ID attribute with the specified value.

Backed by a lazily-built id -> element index that is rebuilt only after a DOM mutation, so repeated lookups on a static document are O(1).

Parameters:

_id (str) – The value of the ID attribute.

Returns:

The element that has the ID attribute with the specified value.

Return type:

Element | None

getElementsByName(name)[source]

Returns a NodeList containing all elements with a specified name.

Parameters:

name (str) – The name to search for.

Returns:

The matching elements.

Return type:

HTMLCollection

property head: HTMLHeadElement | None

Returns the <head> element of the document

property images

A live HTMLCollection of the document’s <img> elements.

property implementation

Returns the DOMImplementation object that handles this document

importNode(node, deep=False)[source]

Imports a node from another document to this document.

property lastModified: str
property links

A live HTMLCollection of the document’s <a href> and <area href> elements.

nodeType: int = 9
normalizeDocument()[source]

Removes empty Text nodes, and joins adjacent nodes

open(index=None, *args, **kwargs)[source]

Start a new parse (https://html.spec.whatwg.org/#dom-document-open): the document is emptied, readyState becomes "loading", and markup passed to write() is parsed into it incrementally until close(). A call while a parse is already open changes nothing.

index is a domonic extension: a file path that also receives everything written.

property referrer: str
renameNode(node, namespaceURI, nodename)[source]

Renames the specified node, and returns the renamed node.

Parameters:
  • node (Node) – The node to rename.

  • namespaceURI (str) – A namespace URI.

  • nodename (str) – A node name.

Returns:

The renamed node, or False if node is not an element.

Return type:

Node | bool

property pictureInPictureEnabled

Returns whether Picture-in-Picture mode is enabled.

property scripts

A live HTMLCollection of the document’s <script> elements.

strictErrorChecking()[source]

Returns a Boolean value indicating whether to stop on the first error

property title: str

Gets the title of the document.

Returns:

The title of the document.

Return type:

str

property visibilityState

Returns the visibility state of the document

write(html='')[source]

Parse html into the document (https://html.spec.whatwg.org/#dom-document-write).

Text or UTF-8 bytes, in chunks of any size. Without an open() first the document is opened (and so emptied) for you, as in a browser. Everything written accumulates until close(); between writes the document is live.

writeln(html='')[source]

Writes HTML text to a document, followed by a line break.

Parameters:

html (str, optional) – The content to write to the document.

append(*items)
Return type:

Any

clear()
property contents: list[Any]
decode(*args, **kwargs)

Beautiful Soup’s .decode() - the string form of the tree.

Return type:

str

decompose()
property descendants: Iterator[Any]
encode(encoding='utf-8', *args, **kwargs)

Beautiful Soup’s .encode() - the byte form of the tree.

Return type:

bytes

extend(items)
extract()
Return type:

Node

find(name=None, attrs=None, recursive=True, string=None, **kwargs)
Return type:

Any | None

findAll(name=None, attrs=None, recursive=True, string=None, limit=None, **kwargs)
Return type:

list[Any]

findAllNext(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findAllPrevious(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findChild(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findChildren(name=None, attrs=None, limit=None, string=None, **kwargs)
Return type:

list[Any]

findNext(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findNextSibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findNextSiblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findParent(name=None, attrs=None, **kwargs)
Return type:

Any | None

findParents(name=None, attrs=None, limit=None, **kwargs)
Return type:

list[Any]

findPrevious(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findPreviousSibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findPreviousSiblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all(name=None, attrs=None, recursive=True, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all_next(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all_previous(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_child(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_children(name=None, attrs=None, limit=None, string=None, **kwargs)
Return type:

list[Any]

find_next(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_next_sibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_next_siblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_parent(name=None, attrs=None, **kwargs)
Return type:

Any | None

find_parents(name=None, attrs=None, limit=None, **kwargs)
Return type:

list[Any]

find_previous(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_previous_sibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_previous_siblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

getText(separator='', strip=False, types=None)
Return type:

str

get_text(separator='', strip=False, types=None)
Return type:

str

insert(index, item)
Return type:

Any

insert_after(item)
Return type:

Any

insert_before(item)
Return type:

Any

new_string(value='')
Return type:

Text

new_tag(name, namespace=None, nsprefix=None, attrs=None, **kwargs)
Return type:

Element

property next_element: Any | None
property next_elements: Iterator[Any]
property next_sibling: Any | None
property next_siblings: Iterator[Any]
property parent: Node | None
property parents: Iterator[Node]
prettify(formatter='minimal', indent=' ')

Beautiful Soup’s prettify() – one node per line, indent per level.

Linear in the document size (the old implementation went through Node.__format__, which recomputed each node’s depth by walking its parent chain – O(n * depth)).

Return type:

str

property previous_element: Any | None
property previous_elements: Iterator[Any]
property previous_sibling: Any | None
property previous_siblings: Iterator[Any]
replace_with(*nodes)
Return type:

Node

select(selector, limit=None, **kwargs)
Return type:

list[Element]

select_one(selector, **kwargs)
Return type:

Element | None

smooth()
property string: str | Text | None
property strings: Iterator[str]
property stripped_strings: Iterator[str]
unwrap()
Return type:

Node

wrap(wrapper)
Return type:

Element

class domonic.dom.Location(url=None, *args, **kwargs)[source]

Bases: object

href: str
origin()[source]

Returns the protocol, hostname and port number of a URL

search()[source]

Sets or returns the querystring part of a URL

assign(url='')[source]

Loads a new document

reload()[source]

Reloads the current document

replace(url='')[source]

Replaces the current document with a new one

domonic.dom.location

alias of Location

class domonic.dom.DocumentFragment(*args)[source]

Bases: Node

nodeType: int = 11
property children: NodeList

Returns a live collection of child nodes, excluding string content.

property childElementCount: int

Returns the number of child elements an element has

property firstElementChild

First Element child node.

property lastElementChild

Last Element child node.

querySelector(query)

Returns the first child element that matches a specified CSS selector(s) of an element.

Parameters:

query (str) – A CSS selector string.

Returns:

The first matching Element, or None.

Return type:

Element | None

querySelectorAll(query)

Returns all child elements that match a specified CSS selector(s) of an element.

Parameters:

query (str) – A CSS selector string.

Returns:

A list of matching Element objects.

Return type:

list[Element]

getElementById(_id)

Returns the element that has the ID attribute with the specified value.

Backed by a lazily-built id -> element index that is rebuilt only after a DOM mutation, so repeated lookups on a static document are O(1).

Parameters:

_id (str) – The value of the ID attribute.

Returns:

The element that has the ID attribute with the specified value.

Return type:

Element | None

getElementsByTagName(tagName)

Returns a collection of all child elements with the specified tag name.

Parameters:

tagName (str) – A DOMString representing the tag name to match.

Returns:

A live HTMLCollection of elements with the given tag name.

Return type:

HTMLCollection

getElementsByClassName(className)

Returns a collection of all child elements with the specified class name.

Parameters:

className (str) – A DOMString representing the class name to match.

Returns:

All child elements with the specified class name.

Return type:

HTMLCollection

property attributes: NamedNodeMap

Returns a NamedNodeMap of an element’s attributes

append(*items)
Return type:

Any

prepend(*nodes)[source]

Prepends nodes or strings to the DocumentFragment.

replaceChildren(*newChildren)[source]

Replaces the childNodes of the DocumentFragment object.

stream()[source]

Yield rendered HTML chunks without materialising the full subtree.

Return type:

Iterator[str]

clear()
property contents: list[Any]
decode(*args, **kwargs)

Beautiful Soup’s .decode() - the string form of the tree.

Return type:

str

decompose()
property descendants: Iterator[Any]
encode(encoding='utf-8', *args, **kwargs)

Beautiful Soup’s .encode() - the byte form of the tree.

Return type:

bytes

extend(items)
extract()
Return type:

Node

find(name=None, attrs=None, recursive=True, string=None, **kwargs)
Return type:

Any | None

findAll(name=None, attrs=None, recursive=True, string=None, limit=None, **kwargs)
Return type:

list[Any]

findAllNext(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findAllPrevious(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findChild(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findChildren(name=None, attrs=None, limit=None, string=None, **kwargs)
Return type:

list[Any]

findNext(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findNextSibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findNextSiblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findParent(name=None, attrs=None, **kwargs)
Return type:

Any | None

findParents(name=None, attrs=None, limit=None, **kwargs)
Return type:

list[Any]

findPrevious(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findPreviousSibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findPreviousSiblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all(name=None, attrs=None, recursive=True, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all_next(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all_previous(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_child(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_children(name=None, attrs=None, limit=None, string=None, **kwargs)
Return type:

list[Any]

find_next(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_next_sibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_next_siblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_parent(name=None, attrs=None, **kwargs)
Return type:

Any | None

find_parents(name=None, attrs=None, limit=None, **kwargs)
Return type:

list[Any]

find_previous(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_previous_sibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_previous_siblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

getText(separator='', strip=False, types=None)
Return type:

str

get_text(separator='', strip=False, types=None)
Return type:

str

insert(index, item)
Return type:

Any

insert_after(item)
Return type:

Any

insert_before(item)
Return type:

Any

new_string(value='')
Return type:

Text

new_tag(name, namespace=None, nsprefix=None, attrs=None, **kwargs)
Return type:

Element

property next_element: Any | None
property next_elements: Iterator[Any]
property next_sibling: Any | None
property next_siblings: Iterator[Any]
property parent: Node | None
property parents: Iterator[Node]
prettify(formatter='minimal', indent=' ')

Beautiful Soup’s prettify() – one node per line, indent per level.

Linear in the document size (the old implementation went through Node.__format__, which recomputed each node’s depth by walking its parent chain – O(n * depth)).

Return type:

str

property previous_element: Any | None
property previous_elements: Iterator[Any]
property previous_sibling: Any | None
property previous_siblings: Iterator[Any]
replace_with(*nodes)
Return type:

Node

select(selector, limit=None, **kwargs)
Return type:

list[Element]

select_one(selector, **kwargs)
Return type:

Element | None

smooth()
property string: str | Text | None
property strings: Iterator[str]
property stripped_strings: Iterator[str]
unwrap()
Return type:

Node

wrap(wrapper)
Return type:

Element

class domonic.dom.CharacterData(*args, **kwargs)[source]

Bases: Node

The CharacterData abstract interface represents a Node object that contains characters. This is an abstract interface, meaning there aren’t any objects of type CharacterData: it is implemented by other interfaces like Text, Comment, or ProcessingInstruction, which aren’t abstract.

property nextElementSibling: Node | None

Returns the next element at the same node tree level

property previousElementSibling: Node | None

returns the Element immediately prior to the specified one in its parent’s children list, or None if the specified element is the first one in the list.

remove()

Removes this ChildNode from the children list of its parent.

replaceWith(*nodes)

Replaces this ChildNode with one or more nodes or strings.

before(*nodes)

Inserts one or more nodes or strings immediately before this ChildNode.

after(*nodes)

Inserts one or more nodes or strings immediately after this ChildNode.

property length: int
property nodeValue: str

Sets or returns the value of a node

property textContent: str

Returns the text content of a node and its descendants

appendData(data)[source]

Appends the given DOMString to the CharacterData.data string; when this method returns, data contains the concatenated DOMString.

deleteData(offset, count)[source]

Removes the specified amount of characters, starting at the specified offset, from the CharacterData.data string; when this method returns, data contains the shortened DOMString.

insertData(offset, data)[source]

Inserts the specified characters, at the specified offset, in the CharacterData.data string; when this method returns, data contains the modified DOMString.

replaceData(offset, count, data)[source]

Replaces the specified amount of characters, starting at the specified offset, with the specified DOMString; when this method returns, data contains the modified DOMString.

substringData(offset, length)[source]

Returns a DOMString containing the part of CharacterData.data of the specified length and starting at the specified offset.

class domonic.dom.EntityReference(*args)[source]

Bases: Node

The EntityReference interface represents a reference to an entity, either parsed or unparsed, in an Entity Node. Note that this is not a CharacterData node, and does not have any child nodes.

stream()[source]

Yield rendered HTML chunks without materialising the full subtree.

Return type:

Iterator[str]

static ordinal(entityName)[source]

Returns the character corresponding to the given entity name.

static fromOrdinal(ordinal)[source]

Returns the entity name corresponding to the given character.

class domonic.dom.Entity(name='', publicId=None, systemId=None, notationName=None)[source]

Bases: Node

A DTD entity declaration.

nodeType: int = 6
nodeValue = None
actualEncoding = None
encoding = None
version = None
property nodeName: str

The entity name.

stream()[source]

Yield rendered HTML chunks without materialising the full subtree.

Return type:

Iterator[str]

static fromName(entityName)[source]

Returns the entity name corresponding to the given character.

Return type:

str

static fromChar(char)[source]

Returns the character corresponding to the given entity name.

Return type:

str

class domonic.dom.Notation(name='', publicId=None, systemId=None)[source]

Bases: Node

A DTD notation declaration.

nodeType: int = 12
nodeValue = None
property nodeName: str

The notation name.

stream()[source]

Yield rendered HTML chunks without materialising the full subtree.

Return type:

Iterator[str]

class domonic.dom.Text(*args, **kwargs)[source]

Bases: CharacterData

Text Node

property wholeText

The concatenated data of this node and the Text nodes contiguous with it (https://dom.spec.whatwg.org/#dom-text-wholetext) – walking siblings both ways until a non-text node breaks the run. domonic’s raw-string children count as text for this purpose.

splitText(offset)[source]

Splits the Text node into two Text nodes at the specified offset, keeping both in the tree as siblings. The first node is returned, while the second node is discarded and exists outside the tree.

property assignedSlot

Returns the slot whose assignedNodes contains this node.

property data
nodeType: int = 3
property nodeName

Returns the name of a node

property childNodes

Returns a live NodeList containing all the children of this node

property firstChild

Returns the first child node of an element

property lastChild

Returns the last child node of an element

hasChildNodes()[source]

Returns true if an element has any child nodes, otherwise false

Return type:

bool

stream()[source]

Yield rendered HTML chunks without materialising the full subtree.

Return type:

Iterator[str]

append(*items)
Return type:

Any

clear()
property contents: list[Any]
decode(*args, **kwargs)

Beautiful Soup’s .decode() - the string form of the tree.

Return type:

str

decompose()
property descendants: Iterator[Any]
encode(encoding='utf-8', *args, **kwargs)

Beautiful Soup’s .encode() - the byte form of the tree.

Return type:

bytes

extend(items)
extract()
Return type:

Node

find(name=None, attrs=None, recursive=True, string=None, **kwargs)
Return type:

Any | None

findAll(name=None, attrs=None, recursive=True, string=None, limit=None, **kwargs)
Return type:

list[Any]

findAllNext(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findAllPrevious(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findChild(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findChildren(name=None, attrs=None, limit=None, string=None, **kwargs)
Return type:

list[Any]

findNext(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findNextSibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findNextSiblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

findParent(name=None, attrs=None, **kwargs)
Return type:

Any | None

findParents(name=None, attrs=None, limit=None, **kwargs)
Return type:

list[Any]

findPrevious(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findPreviousSibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

findPreviousSiblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all(name=None, attrs=None, recursive=True, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all_next(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_all_previous(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_child(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_children(name=None, attrs=None, limit=None, string=None, **kwargs)
Return type:

list[Any]

find_next(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_next_sibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_next_siblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

find_parent(name=None, attrs=None, **kwargs)
Return type:

Any | None

find_parents(name=None, attrs=None, limit=None, **kwargs)
Return type:

list[Any]

find_previous(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_previous_sibling(name=None, attrs=None, string=None, **kwargs)
Return type:

Any | None

find_previous_siblings(name=None, attrs=None, string=None, limit=None, **kwargs)
Return type:

list[Any]

getText(separator='', strip=False, types=None)
Return type:

str

get_text(separator='', strip=False, types=None)
Return type:

str

insert(index, item)
Return type:

Any

insert_after(item)
Return type:

Any

insert_before(item)
Return type:

Any

new_string(value='')
Return type:

Text

new_tag(name, namespace=None, nsprefix=None, attrs=None, **kwargs)
Return type:

Element

property next_element: Any | None
property next_elements: Iterator[Any]
property next_sibling: Any | None
property next_siblings: Iterator[Any]
property parent: Node | None
property parents: Iterator[Node]
prettify(formatter='minimal', indent=' ')

Beautiful Soup’s prettify() – one node per line, indent per level.

Linear in the document size (the old implementation went through Node.__format__, which recomputed each node’s depth by walking its parent chain – O(n * depth)).

Return type:

str

property previous_element: Any | None
property previous_elements: Iterator[Any]
property previous_sibling: Any | None
property previous_siblings: Iterator[Any]
replace_with(*nodes)
Return type:

Node

select(selector, limit=None, **kwargs)
Return type:

list[Element]

select_one(selector, **kwargs)
Return type:

Element | None

smooth()
property string: str | Text | None
property strings: Iterator[str]
property stripped_strings: Iterator[str]
unwrap()
Return type:

Node

wrap(wrapper)
Return type:

Element

class domonic.dom.HTMLCollection(iterable=(), /)[source]

Bases: list

property length: int
item(index)[source]

Gets the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns None.

Parameters:

index (int) – The index of the item to return.

Returns:

The node at the indexth position, or None.

Return type:

Node | None

namedItem(name)[source]

Returns the specific node whose ID or, as a fallback, name matches the string specified by name.

Return type:

Node | None

class domonic.dom.MutationRecord(type, target, *, addedNodes=(), removedNodes=(), previousSibling=None, nextSibling=None, attributeName=None, attributeNamespace=None, oldValue=None)[source]

Bases: object

Single mutation payload delivered to a MutationObserver.

Records describe one child-list, attribute, or character-data change and carry the pieces of context the observer asked to receive.

type
target
addedNodes
removedNodes
previousSibling
nextSibling
attributeName
attributeNamespace
oldValue
class domonic.dom.MutationObserver(callback)[source]

Bases: object

Observe DOM tree mutations and receive MutationRecord batches.

This implementation follows the familiar platform model: call observe() with a target and options, allow DOM operations to queue records, then receive them through the callback or takeRecords(). Callbacks currently run synchronously after each mutation; browser microtask batching is not implemented. Call disconnect() to release an active registration.

disconnect()[source]
observe(target, options)[source]
takeRecords()[source]
Return type:

list[MutationRecord]

class domonic.dom.ResizeObserverSize(inlineSize, blockSize)[source]

Bases: object

Inline and block dimensions reported by ResizeObserver entries.

class domonic.dom.ResizeObserverEntry(target, contentRect)[source]

Bases: object

Geometry snapshot for a single observed element resize.

class domonic.dom.ResizeObserver(callback)[source]

Bases: object

Observe element box changes through DOM geometry reads.

Domonic treats layout changes pragmatically: when relevant geometry changes are computed, resize entries are queued and delivered to the callback.

observe(target, options=None)[source]
unobserve(target)[source]
disconnect()[source]
takeRecords()[source]
Return type:

list[ResizeObserverEntry]

class domonic.dom.IntersectionObserverEntry(target, rootBounds, boundingClientRect, intersectionRect, time_value)[source]

Bases: object

Visibility snapshot for one target observed by IntersectionObserver.

class domonic.dom.IntersectionObserver(callback, options=None)[source]

Bases: object

Observe whether elements intersect a root rectangle or viewport-like area.

Domonic models intersections using element bounding boxes and a root rectangle, which is enough for practical DOM-side visibility checks and tests.

observe(target)[source]
unobserve(target)[source]
disconnect()[source]
takeRecords()[source]
Return type:

list[IntersectionObserverEntry]

exception domonic.dom.DOMException(code=None, message=None)[source]

Bases: ValueError

The DOMException interface represents an anormal event related to the DOM.

Subclasses ValueError for backwards compatibility: domonic historically raised a plain ValueError for tree-mutation failures, so code that catches ValueError keeps working while new code can branch on .name ("HierarchyRequestError", "NotFoundError", …) as in the browser.

INDEX_SIZE_ERR: int = 1
DOMSTRING_SIZE_ERR: int = 2
HIERARCHY_REQUEST_ERR: int = 3
WRONG_DOCUMENT_ERR: int = 4
INVALID_CHARACTER_ERR: int = 5
NO_DATA_ALLOWED_ERR: int = 6
NO_MODIFICATION_ALLOWED_ERR: int = 7
NOT_FOUND_ERR: int = 8
NOT_SUPPORTED_ERR: int = 9
INUSE_ATTRIBUTE_ERR: int = 10
INVALID_STATE_ERR: int = 11
SYNTAX_ERR: int = 12
INVALID_MODIFICATION_ERR: int = 13
NAMESPACE_ERR: int = 14
INVALID_ACCESS_ERR: int = 15
VALIDATION_ERR: int = 16
TYPE_MISMATCH_ERR: int = 17
SECURITY_ERR: int = 18
NETWORK_ERR: int = 19
ABORT_ERR: int = 20
URL_MISMATCH_ERR: int = 21
QUOTA_EXCEEDED_ERR: int = 22
TIMEOUT_ERR: int = 23
INVALID_NODE_TYPE_ERR: int = 24
DATA_CLONE_ERR: int = 25
code: int
message: str
name: str
class domonic.dom.DOMTimeStamp(value)[source]

Bases: int

The DOMTimeStamp interface represents a numeric value which represents the number of milliseconds since the epoch.

class domonic.dom.DOMPoint(x, y, z=0, w=1)[source]

Bases: vec3

The DOMPoint interface represents a point specified by x and y coordinates.

static fromPoint(point)[source]
Return type:

DOMPoint

x: float
y: float
z: float
w: float
class domonic.dom.DOMPointReadOnly(x, y, z=0, w=1)[source]

Bases: DOMPoint

The DOMPointReadOnly interface represents a point specified by x and y coordinates.

static fromPoint(point)[source]
Return type:

DOMPointReadOnly

x: float
y: float
z: float
w: float
class domonic.dom.DOMMatrixReadOnly(*values)[source]

Bases: object

Read-only 4x4 transformation matrix for DOM geometry APIs.

Supports the common 2D aliases as well as the full 4x4 member set used by transforms, points, and animation/geometry helpers.

property m11
property m12
property m13
property m14
property m21
property m22
property m23
property m24
property m31
property m32
property m33
property m34
property m41
property m42
property m43
property m44
static fromFloat64Array(array)[source]
Return type:

DOMMatrixReadOnly

static fromFloat32Array(array)[source]
Return type:

DOMMatrixReadOnly

static fromMatrix(matrix=None)[source]
Return type:

DOMMatrixReadOnly

property is2D: bool
property isIdentity: bool
property a: float
property b: float
property c: float
property d: float
property e: float
property f: float
toFloat64Array()[source]
Return type:

list[float]

toFloat32Array()[source]
Return type:

list[float]

toJSON()[source]
Return type:

dict[str, float | bool]

multiply(other)[source]
Return type:

DOMMatrix

translate(tx=0, ty=0, tz=0)[source]
Return type:

DOMMatrix

scale(scaleX=1, scaleY=None, scaleZ=1)[source]
Return type:

DOMMatrix

inverse()[source]
Return type:

DOMMatrix

rotate(rotX=0, rotY=None, rotZ=None)[source]
Return type:

DOMMatrix

skewX(sx=0)[source]
Return type:

DOMMatrix

skewY(sy=0)[source]
Return type:

DOMMatrix

transformPoint(point=None)[source]
Return type:

DOMPoint

class domonic.dom.DOMMatrix(*values)[source]

Bases: DOMMatrixReadOnly

Mutable DOMMatrix implementation.

Use this when you want to construct, compose, invert, or transform points with a matrix that can be updated in place.

static fromFloat64Array(array)[source]
Return type:

DOMMatrix

static fromFloat32Array(array)[source]
Return type:

DOMMatrix

static fromMatrix(matrix=None)[source]
Return type:

DOMMatrix

property a: float
property b: float
property c: float
property d: float
property e: float
property f: float
multiplySelf(other)[source]

self = self . other (post-multiply), matching the spec: a.multiplySelf(b) transforms a point as a.transformPoint( b.transformPoint(p)) – b is applied first.

_values stores each matrix pre-transposed (row r, column c lives at _values[r*4+c], but a point is transformed as p . _values – see transformPoint): storing Aᵀ for spec matrix A. Composing spec matrices as A · B therefore means storing (A · B)ᵀ = Bᵀ · Aᵀ – other’s (transposed) storage on the left of the raw row-major product, self’s on the right.

Return type:

DOMMatrix

translateSelf(tx=0, ty=0, tz=0)[source]
Return type:

DOMMatrix

scaleSelf(scaleX=1, scaleY=None, scaleZ=1)[source]
Return type:

DOMMatrix

rotateSelf(rotX=0, rotY=None, rotZ=None)[source]
Return type:

DOMMatrix

rotateFromVectorSelf(x=0, y=0)[source]
Return type:

DOMMatrix

skewXSelf(sx=0)[source]
Return type:

DOMMatrix

skewYSelf(sy=0)[source]
Return type:

DOMMatrix

toString()[source]
Return type:

str

invertSelf()[source]
Return type:

DOMMatrix

property m11
property m12
property m13
property m14
property m21
property m22
property m23
property m24
property m31
property m32
property m33
property m34
property m41
property m42
property m43
property m44
class domonic.dom.DOMQuad(p1, p2, p3, p4)[source]

Bases: object

The DOMQuad interface represents a quadrilateral on the plane with its four corners represented as Cartesian coordinates.

static fromRect(rect)[source]
Return type:

DOMQuad

static fromQuad(quad)[source]
Return type:

DOMQuad

static getBounds(quad)[source]
Return type:

DOMRect

static toJSON(quad)[source]
Return type:

dict[str, dict[str, float]]

class domonic.dom.NodeFilter[source]

Bases: object

SHOW_ALL: int = 4294967295
SHOW_ELEMENT: int = 1
SHOW_ATTRIBUTE: int = 2
SHOW_TEXT: int = 4
SHOW_CDATA_SECTION: int = 8
SHOW_ENTITY_REFERENCE: int = 16
SHOW_ENTITY: int = 32
SHOW_PROCESSING_INSTRUCTION: int = 64
SHOW_COMMENT: int = 128
SHOW_DOCUMENT: int = 256
SHOW_DOCUMENT_TYPE: int = 512
SHOW_DOCUMENT_FRAGMENT: int = 1024
SHOW_NOTATION: int = 2048
FILTER_ACCEPT: int = 1
FILTER_REJECT: int = 2
FILTER_SKIP: int = 3
class domonic.dom.NodeIterator(root, whatToShow=4294967295, filter=None, entityReferenceExpansion=False)[source]

Bases: object

NodeIterator is an iterator object that iterates over the descendants of a node, in tree order.

stack: list[Node]
property filter: Any
toString()[source]
Return type:

str

property referenceNode: Node

a read-only attribute, not a method).

Type:

The node the iterator is currently anchored to (DOM spec

property pointerBeforeReferenceNode: bool

True while the iterator sits before referenceNode, False while it sits after it (DOM spec: a read-only attribute).

detach()[source]
previousNode()[source]

Returns the previous Node in the document, or null if there are none.

Return type:

Node | None

nextNode()[source]

Returns the next Node in the document, or null if there are none.

Return type:

Node | None

domonic.dom.nodeFilter(tw, node)[source]
Return type:

int

domonic.dom.str_to_TextNode(content_str)[source]
Return type:

Any

domonic.dom.traverseChildren(tw, _type)[source]
Return type:

Node | None

domonic.dom.traverseSiblings(tw, type)[source]
Return type:

Node | None

domonic.dom.nextSkippingChildren(node, stayWithin)[source]
Return type:

Node | None

class domonic.dom.TreeWalker(node, whatToShow=4294967295, _filter=None, expandEntityReferences=False)[source]

Bases: object

The TreeWalker object represents the nodes of a document subtree and a position within them.

children: list[Node]
tree

Is a boolean value indicating, when discarding an entity reference its whole sub-tree must be discarded at the same time.

property currentNode: Node

The Node the TreeWalker is currently positioned on.

property root: Node

Returns a Node representing the root node as specified when the TreeWalker was created.

property filter: Any

The NodeFilter / callable given at construction (None if none).

toString()[source]
Return type:

str

parentNode()[source]

Moves the current Node to the first visible ancestor node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists, or if it is before that the root node defined at the object construction, returns null and the current node is not changed.

Return type:

Node | None

firstChild()[source]

Moves the current Node to the first visible child of the current node, and returns the found child. It also moves the current node to this child. If no such child exists, returns null and the current node is not changed.

Return type:

Node | None

lastChild()[source]

Moves the current Node to the last visible child of the current node, and returns the found child. It also moves the current node to this child. If no such child exists, null is returned and the current node is not changed.

Return type:

Node | None

previousSibling()[source]

Moves the current Node to its previous sibling, if any, and returns the found sibling. If there is no such node, return null and the current node is not changed.

Return type:

Node | None

nextSibling()[source]

Moves the current Node to its next sibling, if any, and returns the found sibling. If there is no such node, null is returned and the current node is not changed.

Return type:

Node | None

previousNode()[source]

Moves the current Node to the previous visible node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists, or if it is before that the root node defined at the object construction, returns null and the current node is not changed.

nextNode()[source]

Moves the current Node to the next visible node in the document order, and returns the found node. It also moves the current node to this one. If no such node exists, returns None and the current node is not changed. can be used in a while loop to iterate over all the nodes in the document order.

class domonic.dom.DOMParser[source]

Bases: object

new DOMParser().parseFromString(markup, mimeType) – parse a string into a document, mirroring the browser API.

parseFromString(string, mimeType='text/html')[source]
Return type:

Node

class domonic.dom.XMLSerializer[source]

Bases: object

new XMLSerializer().serializeToString(node) – serialise a node back to markup.

serializeToString(node)[source]
Return type:

str

class domonic.dom.Sanitizer(*args, **kwargs)[source]

Bases: object

Backward-compatible proxy for domonic.webapi.sanitizer.Sanitizer.

static getDefaultConfiguration()[source]
class domonic.dom.MathMLElement(*args, **kwargs)[source]

Bases: Element

DOM interface for MathML elements.

name: str = ''
property nonce: str | None
class domonic.dom.HTMLElement(*args, **kwargs)[source]

Bases: Element

name: str = ''
property form: HTMLFormElement | None

The <form> this form-associated control belongs to (via a form= attribute pointing at a form id, or the nearest ancestor <form>), or None (https://html.spec.whatwg.org/#dom-fae-form).

property validity: ValidityState
property validationMessage: str
property willValidate: bool
checkValidity()[source]
Return type:

bool

reportValidity()[source]
Return type:

bool

setCustomValidity(message)[source]
property popover: str | None

//html.spec.whatwg.org/#attr-popover): "auto", "manual" or "hint". An empty value means auto, any other value means manual, and a missing attribute is None.

Type:

The popover attribute’s state (https

showPopover()[source]
hidePopover()[source]
togglePopover(force=None)[source]
class domonic.dom.HTMLAnchorElement(*args, href=None, target=None, rel=None, download=None, hreflang=None, ping=None, referrerpolicy=None, type=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'a'
property interestForElement: Element | None
class domonic.dom.HTMLAreaElement(*args, href=None, target=None, alt=None, coords=None, download=None, ping=None, rel=None, referrerpolicy=None, shape=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'area'
property interestForElement: Element | None
class domonic.dom.HTMLAudioElement(*args, autoplay=None, controls=None, crossorigin=None, loading=None, loop=None, muted=None, preload=None, src=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'audio'
class domonic.dom.HTMLBRElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'br'
stream()[source]

Yield rendered HTML chunks without materialising the full subtree.

Return type:

Iterator[str]

class domonic.dom.HTMLBaseElement(*args, href=None, target=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'base'
class domonic.dom.HTMLBaseFontElement(*args, color=None, face=None, size=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'basefont'
class domonic.dom.HTMLBodyElement(*args, aLink=None, background=None, bgColor=None, link=None, onload=None, onunload=None, text=None, vLink=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'body'
class domonic.dom.HTMLButtonElement(*args, command=None, commandfor=None, disabled=None, form=None, formaction=None, formenctype=None, formmethod=None, formnovalidate=None, formtarget=None, name=None, popovertarget=None, popovertargetaction=None, type=None, value=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'button'
property popoverTargetElement: Element | None
property popoverTargetAction: str | None
property interestForElement: Element | None
property value: str
click()[source]

Simulates a mouse-click on an element

class domonic.dom.HTMLCanvasElement(*args, width=None, height=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'canvas'
getContext(contextId, options=None)[source]

Return a 2D, WebGL, or WebGL2 context for the canvas.

Return type:

Any

toDataURL(type='image/png', quality=None)[source]

Return a data URL describing the current canvas command state.

Return type:

str

toBlob(callback=None, type='image/png', quality=None)[source]

Create a Blob for the canvas data and optionally pass it to a callback.

captureStream(frameRate=None)[source]

Return a simple video MediaStream for canvas capture examples.

transferControlToOffscreen()[source]

Return an OffscreenCanvas with the same dimensions.

class domonic.dom.HTMLContentElement(*args, select=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'content'
class domonic.dom.HTMLDListElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'dl'
class domonic.dom.HTMLDataElement(*args, value=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'data'
class domonic.dom.HTMLDataListElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'datalist'
class domonic.dom.HTMLDialogElement(*args, open=None, closedby=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'dialog'
property open: bool
show()[source]
showModal()[source]
close(returnValue='')[source]
class domonic.dom.HTMLDivElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'div'
class domonic.dom.XMLDocument(*args, **kwargs)[source]

Bases: Document

name: str = 'xml'
contentType: str = 'application/xml'
class domonic.dom.HTMLDocument(*args, **kwargs)[source]

Bases: Document

name: str = 'html'
contentType: str = 'text/html'
static createCDATASection(data)[source]

https://dom.spec.whatwg.org/#dom-document-createcdatasection – CDATA sections are an XML-only construct; an HTML document must refuse to create one.

Return type:

CDATASection

class domonic.dom.HTMLEmbedElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'embed'
class domonic.dom.HTMLFieldSetElement(*args, disabled=None, form=None, name=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'fieldset'
class domonic.dom.HTMLFormControlsCollection(form)[source]

Bases: HTMLCollection

Live collection of a form’s listed controls.

CONTROL_TYPES: ClassVar[tuple[type[HTMLElement], ...]] = (<class 'domonic.dom.HTMLButtonElement'>, <class 'domonic.dom.HTMLFieldSetElement'>, <class 'domonic.dom.HTMLInputElement'>, <class 'domonic.dom.HTMLObjectElement'>, <class 'domonic.dom.HTMLOutputElement'>, <class 'domonic.dom.HTMLSelectElement'>, <class 'domonic.dom.HTMLTextAreaElement'>)
property length: int
item(index)[source]

Gets the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns None.

Parameters:

index (int) – The index of the item to return.

Returns:

The node at the indexth position, or None.

Return type:

Node | None

namedItem(name)[source]

Returns the specific node whose ID or, as a fallback, name matches the string specified by name.

Return type:

HTMLElement | RadioNodeList | None

class domonic.dom.HTMLFormElement(*args, action=None, accept_charset=None, autocomplete=None, enctype=None, method=None, name=None, novalidate=None, rel=None, target=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'form'
submit()[source]
checkValidity()[source]
Return type:

bool

requestSubmit(submitter=None)[source]
reset()[source]
reportValidity()[source]
Return type:

bool

property elements: HTMLFormControlsCollection
class domonic.dom.HTMLFrameSetElement(*args, cols=None, rows=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'frameset'
class domonic.dom.HTMLHRElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'hr'
class domonic.dom.HTMLHeadElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'head'
class domonic.dom.HTMLHeadingElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'h1'
class domonic.dom.HTMLIFrameElement(*args, allow=None, allowfullscreen=None, credentialless=None, height=None, loading=None, name=None, referrerpolicy=None, sandbox=None, src=None, srcdoc=None, width=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'iframe'
class domonic.dom.HTMLImageElement(*args, alt=None, controls=None, crossorigin=None, decoding=None, fetchpriority=None, height=None, ismap=None, loading=None, longdesc=None, referrerpolicy=None, sizes=None, src=None, srcset=None, usemap=None, width=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'img'
load()[source]
decode()[source]

Beautiful Soup’s .decode() - the string form of the tree.

Return type:

bool

error()[source]
abort()[source]
class domonic.dom.HTMLInputElement(*args, accept=None, alpha=None, alt=None, autocomplete=None, autofocus=None, capture=None, checked=None, colorspace=None, dirname=None, disabled=None, form=None, formaction=None, formenctype=None, formmethod=None, formnovalidate=None, formtarget=None, height=None, _list=None, _max=None, maxlength=None, minlength=None, _min=None, multiple=None, name=None, pattern=None, placeholder=None, popovertarget=None, popovertargetaction=None, readonly=None, required=None, size=None, src=None, step=None, type=None, value=None, width=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'input'
property popoverTargetElement: Element | None
property popoverTargetAction: str | None
property type: str
property value: str
property files
setValue(new_value, *, dispatch_events=True)[source]
Return type:

str

property defaultValue: str
property defaultChecked: bool
property checked: bool
click()[source]

Simulates a mouse-click on an element

checkValidity()[source]
Return type:

bool

reportValidity()[source]
Return type:

bool

class domonic.dom.HTMLIsIndexElement(*args, prompt=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'isindex'
class domonic.dom.HTMLKeygenElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'keygen'
class domonic.dom.HTMLLIElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'li'
class domonic.dom.HTMLLabelElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'label'
class domonic.dom.HTMLLegendElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'legend'
class domonic.dom.HTMLLinkElement(*args, as_=None, blocking=None, color=None, crossorigin=None, disabled=None, fetchpriority=None, href=None, hreflang=None, imagesizes=None, imagesrcset=None, integrity=None, media=None, referrerpolicy=None, rel=None, sizes=None, type=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'link'
class domonic.dom.HTMLMapElement(*args, name=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'map'
class domonic.dom.HTMLMediaElement(*args, src=None, crossorigin=None, preload=None, autoplay=None, loop=None, muted=None, controls=None, **kwargs)[source]

Bases: HTMLElement

name: str = ''
textTracks: list[dict[str, Any]]
load()[source]
play()[source]
pause()[source]
addTextTrack(kind, label='', language='')[source]
Return type:

dict[str, Any]

removeTextTrack(track)[source]
class domonic.dom.HTMLMenuElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'menu'
class domonic.dom.HTMLMetaElement(*args, charset=None, content=None, http_equiv=None, name=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'meta'
class domonic.dom.HTMLMeterElement(*args, value=None, _min=None, _max=None, low=None, high=None, optimum=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'meter'
class domonic.dom.HTMLModElement(*args, datetime=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'mod'
class domonic.dom.HTMLOListElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'ol'
class domonic.dom.HTMLObjectElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'object'
class domonic.dom.HTMLOptGroupElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'optgroup'
class domonic.dom.HTMLOptionElement(*args, disabled=None, label=None, selected=None, value=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'option'
property value: str
property selected: bool
property defaultSelected: bool
class domonic.dom.HTMLOptionsCollection(select)[source]

Bases: HTMLCollection

Live collection of a select element’s option descendants.

property length: int
item(index)[source]

Gets the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns None.

Parameters:

index (int) – The index of the item to return.

Returns:

The node at the indexth position, or None.

Return type:

Node | None

namedItem(name)[source]

Returns the specific node whose ID or, as a fallback, name matches the string specified by name.

Return type:

HTMLOptionElement | None

add(element, before=None)[source]
remove(index)[source]

Remove first occurrence of value.

Raises ValueError if the value is not present.

class domonic.dom.HTMLOutputElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'output'
class domonic.dom.HTMLParagraphElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'p'
class domonic.dom.HTMLParamElement(*args, name=None, value=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'param'
class domonic.dom.HTMLPictureElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'picture'
class domonic.dom.HTMLPreElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'pre'
class domonic.dom.HTMLProgressElement(*args, value=None, max=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'progress'
class domonic.dom.HTMLQuoteElement(*args, cite=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'q'
class domonic.dom.HTMLScriptElement(*args, async_=None, blocking=None, crossorigin=None, defer=None, fetchpriority=None, integrity=None, nomodule=None, referrerpolicy=None, src=None, type=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'script'
class domonic.dom.HTMLSelectElement(*args, autofocus=None, disabled=None, multiple=None, name=None, required=None, size=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'select'
property options: HTMLOptionsCollection
property selectedIndex: int
property value: str
property selectedOptions: list[HTMLOptionElement]
setValue(new_value, *, dispatch_events=True)[source]
Return type:

str

selectIndex(index, *, dispatch_events=True)[source]
Return type:

int

checkValidity()[source]
Return type:

bool

reportValidity()[source]
Return type:

bool

class domonic.dom.HTMLSelectedContentElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'selectedcontent'
class domonic.dom.HTMLShadowElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'shadow'
class domonic.dom.HTMLSourceElement(*args, height=None, media=None, sizes=None, src=None, srcset=None, type=None, width=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'source'
class domonic.dom.HTMLSpanElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'span'
class domonic.dom.HTMLStyleElement(*args, blocking=None, media=None, scoped=None, type=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'style'
class domonic.dom.HTMLTableCaptionElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'caption'
class domonic.dom.HTMLTableCellElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'td'
class domonic.dom.HTMLTableColElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'col'
class domonic.dom.HTMLTableDataCellElement(*args, **kwargs)[source]

Bases: HTMLTableCellElement

name: str = 'td'
class domonic.dom.HTMLTableElement(*args, align=None, bgcolor=None, border=None, cellpadding=None, cellspacing=None, frame=None, rules=None, summary=None, width=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'table'
class domonic.dom.HTMLTableHeaderCellElement(*args, **kwargs)[source]

Bases: HTMLTableCellElement

name: str = 'th'
class domonic.dom.HTMLTableRowElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'tr'
class domonic.dom.HTMLTableSectionElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'tbody'
class domonic.dom.HTMLDetailsElement(*args, open=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'details'
property open: bool
toggle()[source]
Return type:

bool

class domonic.dom.HTMLSummaryElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'summary'
class domonic.dom.HTMLSlotElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'slot'
assignedNodes(options=None)[source]
Return type:

list[Node]

assignedElements(options=None)[source]
Return type:

list[Element]

class domonic.dom.HTMLTemplateElement(*args, shadowrootclonable=None, shadowrootcustomelementregistry=None, shadowrootdelegatesfocus=None, shadowrootmode=None, shadowrootserializable=None, shadowrootslotassignment=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'template'
property content
class domonic.dom.HTMLTextAreaElement(*args, autocomplete=None, autofocus=None, cols=None, dirname=None, disabled=None, form=None, maxlength=None, minlength=None, name=None, placeholder=None, readonly=None, required=None, rows=None, wrap=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'textarea'
property value: str
setValue(new_value, *, dispatch_events=True)[source]
Return type:

str

property defaultValue: str
checkValidity()[source]
Return type:

bool

reportValidity()[source]
Return type:

bool

class domonic.dom.HTMLTimeElement(*args, datetime=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'time'
class domonic.dom.HTMLTitleElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'title'
class domonic.dom.HTMLTrackElement(*args, kind=None, label=None, src=None, srclang=None, default=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'track'
class domonic.dom.HTMLUListElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'ul'
class domonic.dom.HTMLUnknownElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'unknown'
class domonic.dom.HTMLVideoElement(*args, autoplay=None, controls=None, controlslist=None, crossorigin=None, disablepictureinpicture=None, height=None, loop=None, muted=None, playsinline=None, poster=None, preload=None, src=None, width=None, **kwargs)[source]

Bases: HTMLElement

name: str = 'video'
class domonic.dom.HTMLPortalElement(*args, **kwargs)[source]

Bases: HTMLElement

name: str = 'portal'

domonic.events

DOM-style event classes and dispatch machinery for domonic.

This module provides EventTarget plus a broad set of web-platform-flavoured event classes so DOM nodes, windows, animations, and helper objects can share a common event model.

class domonic.events.EventListener[source]

Bases: object

Interface-style base for listener objects with handleEvent().

handleEvent(event)[source]

Handle an event passed by EventTarget dispatch.

Return type:

Any

class domonic.events.EventListenerOptions(capture=False, once=False, passive=False, signal=None)[source]

Bases: dict

Dictionary-like helper for DOM listener options.

Supports the common capture, once, passive, and signal fields accepted by addEventListener().

class domonic.events.EventTarget(*args, **kwargs)[source]

Bases: object

DOM-style event target base class.

Extend EventTarget to give an object support for addEventListener(), removeEventListener(), and dispatchEvent() with DOM-like capture, target, and bubble semantics where appropriate.

listeners: dict[str, list[Callable[[...], Any]]]
hasEventListener(eventType)[source]

Check if an event listener for the given event type exists.

Parameters:

eventType (str) – The type of the event.

Returns:

True if listeners for the event type exist, otherwise False.

Return type:

bool

addEventListener(eventType, callback, options=None, *args, **kwargs)[source]

Add an event listener for the given event type.

Parameters:
  • eventType (str) – The type of the event to listen for.

  • callback (Callable) – The callback function to be executed when the event occurs.

  • options (bool | dict[str, Any] | None) – A DOM-style options dictionary or legacy capture boolean.

options may contain capture, once, passive, and signal. Duplicate listeners with the same callback and capture value are ignored, matching DOM listener registration behavior.

removeEventListener(eventType, callback, options=None)[source]

Remove an event listener for the given event type.

Parameters:
  • eventType (str) – The type of the event.

  • callback (Callable) – The callback function to be removed.

  • options (bool | dict[str, Any] | None) – A DOM-style options dictionary or legacy capture boolean.

dispatchEvent(event)[source]

Dispatch the specified event to registered listeners.

Parameters:

event (Any) – An Event instance, event type string, or event mapping.

Returns:

False when a cancelable event had its default prevented, otherwise True.

Return type:

bool

async dispatchEventAsync(event)[source]

Dispatch the specified event to sync and async listeners.

Parameters:

event (Any) – An Event instance, event type string, or event mapping.

Returns:

False when a cancelable event had its default prevented, otherwise True.

Return type:

bool

Usage:

To dispatch an event asynchronously, use the await keyword when calling this method.

Example:

event_data = {"message": "Hello, world!"}
async_event = {"type": "async_event", "data": event_data}
await target.dispatchEventAsync(async_event)
domonic.events.EventDispatcher

legacy alias

class domonic.events.Event(_type='', options=None, *args, **kwargs)[source]

Bases: object

Base DOM event with propagation, cancelation, and path state.

EMPTIED: str = 'emptied'
ABORT: str = 'abort'
ADDTRACK: str = 'addtrack'
AFTERPRINT: str = 'afterprint'
ANIMATIONCANCEL: str = 'animationcancel'
ANIMATIONEND: str = 'animationend'
ANIMATIONITERATION: str = 'animationiteration'
ANIMATIONSTART: str = 'animationstart'
AUXCLICK: str = 'auxclick'
BEFOREINPUT: str = 'beforeinput'
BEFOREMATCH: str = 'beforematch'
BEFOREPRINT: str = 'beforeprint'
BEFORETOGGLE: str = 'beforetoggle'
BEFOREUNLOAD: str = 'beforeunload'
BLUR: str = 'blur'
CANCEL: str = 'cancel'
CANPLAY: str = 'canplay'
CANPLAYTHROUGH: str = 'canplaythrough'
CHANGE: str = 'change'
CLICK: str = 'click'
CLOSE: str = 'close'
COMMAND: str = 'command'
CONNECT: str = 'connect'
CONTEXTLOST: str = 'contextlost'
CONTEXTRESTORED: str = 'contextrestored'
CURRENTENTRYCHANGE: str = 'currententrychange'
DATAAVAILABLE: str = 'dataavailable'
DEVICELIGHT: str = 'devicelight'
DEVICEMOTION: str = 'devicemotion'
DEVICEORIENTATION: str = 'deviceorientation'
DEVICEORIENTATIONABSOLUTE: str = 'deviceorientationabsolute'
DEVICEPROXIMITY: str = 'deviceproximity'
DISPOSE: str = 'dispose'
DOMCONTENTLOADED: str = 'DOMContentLoaded'
DURATIONCHANGE: str = 'durationchange'
ENDED: str = 'ended'
ERROR: str = 'error'
FOCUS: str = 'focus'
FORMDATA: str = 'formdata'
FULLSCREENCHANGE: str = 'fullscreenchange'
FULLSCREENERROR: str = 'fullscreenerror'
HASHCHANGE: str = 'hashchange'
INPUT: str = 'input'
INVALID: str = 'invalid'
LANGUAGECHANGE: str = 'languagechange'
LOAD: str = 'load'
LOADEDDATA: str = 'loadeddata'
LOADEDMETADATA: str = 'loadedmetadata'
MESSAGE: str = 'message'
MESSAGEERROR: str = 'messageerror'
MOUSEENTER: str = 'mouseenter'
MOUSELEAVE: str = 'mouseleave'
NAVIGATE: str = 'navigate'
NAVIGATEERROR: str = 'navigateerror'
NAVIGATESUCCESS: str = 'navigatesuccess'
OFFLINE: str = 'offline'
ONLINE: str = 'online'
OPEN: str = 'open'
PAGEHIDE: str = 'pagehide'
PAGEREVEAL: str = 'pagereveal'
PAGESHOW: str = 'pageshow'
PAGESWAP: str = 'pageswap'
PAUSE: str = 'pause'
PLAY: str = 'play'
PLAYING: str = 'playing'
POINTERCANCEL: str = 'pointercancel'
POPSTATE: str = 'popstate'
PROGRESS: str = 'progress'
RATECHANGE: str = 'ratechange'
READYSTATECHANGE: str = 'readystatechange'
REMOVETRACK: str = 'removetrack'
RESIZE: str = 'resize'
REJECTIONHANDLED: str = 'rejectionhandled'
RESET: str = 'reset'
SCROLL: str = 'scroll'
SCROLLEND: str = 'scrollend'
SEARCH: str = 'search'
SECURITYPOLICYVIOLATION: str = 'securitypolicyviolation'
SEEKED: str = 'seeked'
SEEKING: str = 'seeking'
SELECT: str = 'select'
SHOW: str = 'show'
SLOTCHANGE: str = 'slotchange'
STALLED: str = 'stalled'
STORAGE: str = 'storage'
SUBMIT: str = 'submit'
SUSPEND: str = 'suspend'
TOOLACTIVATED: str = 'toolactivated'
TOOLCANCEL: str = 'toolcancel'
TOOLCHANGE: str = 'toolchange'
TOGGLE: str = 'toggle'
TRANSITIONCANCEL: str = 'transitioncancel'
TRANSITIONEND: str = 'transitionend'
UNHANDLEDREJECTION: str = 'unhandledrejection'
UNLOAD: str = 'unload'
VISIBILITYCHANGE: str = 'visibilitychange'
VOLUMECHANGE: str = 'volumechange'
WAITING: str = 'waiting'
WEBGLCONTEXTCREATIONERROR: str = 'webglcontextcreationerror'
WEBGLCONTEXTLOST: str = 'webglcontextlost'
WEBGLCONTEXTRESTORED: str = 'webglcontextrestored'
NONE: int = 0
CAPTURING_PHASE: int = 1
AT_TARGET: int = 2
BUBBLING_PHASE: int = 3
error: Any
matches: Any
media: Any
type: str
bubbles: bool
cancelable: bool
composed: bool
currentTarget: object
defaultPrevented: bool
eventPhase: int
explicitOriginalTarget: object
isTrusted: bool
originalTarget: object
srcElement: object
target: object
timeStamp: float
property cancelBubble: bool
property returnValue: bool
composedPath()[source]

Return the event path captured during dispatch.

Return type:

list[Any]

initEvent(_type=None, bubbles=False, cancelable=False, *args, **kwargs)[source]

Reinitialize the event when it is not currently dispatching.

Return type:

Event

stopPropagation()[source]

Prevent further propagation in the capture and bubble phases.

msConvertURL(url)[source]

Convert a URL using domonic’s legacy Microsoft-style helper.

Parameters:

url (str) – The URL to be converted.

Returns:

A javascript:window.open(...) wrapper for HTTP(S) URLs, otherwise the original URL.

Return type:

str

preventDefault()[source]

Mark the default action as prevented when the event is cancelable.

stopImmediatePropagation()[source]

Stop propagation and skip remaining listeners on the current target.

class domonic.events.AbortSignal[source]

Bases: EventTarget

Signal object used to communicate cancellation (https://dom.spec.whatwg.org/#interface-AbortSignal).

aborted: bool
reason: Any
static abort(reason=None)[source]

Return an AbortSignal that is already aborted.

Return type:

AbortSignal

static timeout(milliseconds)[source]

Return a signal that aborts with a TimeoutError after milliseconds. The timer runs on a daemon thread.

Return type:

AbortSignal

static any(signals)[source]

Return a signal that aborts as soon as any signal in signals aborts, adopting that signal’s reason.

Return type:

AbortSignal

throwIfAborted()[source]

Raise this signal’s reason if it is aborted – the reason itself when it is an exception, otherwise wrapped in RuntimeError.

class domonic.events.AbortController[source]

Bases: object

Controller used to abort work associated with an AbortSignal.

abort(reason=None)[source]
class domonic.events.UIEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Event carrying view, detail, and UI coordinate context.

initUIEvent(_type, canBubble, cancelable, view, detail)[source]

Initialize a UIEvent with specific parameters.

Parameters:
  • _type (str) – The type of the UIEvent.

  • canBubble (bool) – Specifies whether the event should bubble.

  • cancelable (bool) – Specifies whether the event is cancelable.

  • view – The associated view or window.

  • detail – Additional event-specific detail.

Returns:

The initialized UIEvent object.

Return type:

UIEvent

class domonic.events.MouseEvent(_type, options=None, *args, **kwargs)[source]

Bases: UIEvent

Mouse input event with button, coordinate, and modifier state.

CLICK: str = 'click'
CONTEXTMENU: str = 'contextmenu'
DBLCLICK: str = 'dblclick'
MOUSEDOWN: str = 'mousedown'
MOUSEENTER: str = 'mouseenter'
MOUSELEAVE: str = 'mouseleave'
MOUSEMOVE: str = 'mousemove'
MOUSEOVER: str = 'mouseover'
MOUSEOUT: str = 'mouseout'
MOUSEUP: str = 'mouseup'
initMouseEvent(_type=None, canBubble=True, cancelable=True, view=None, detail=None, screenX=0, screenY=0, clientX=0, clientY=0, ctrlKey=False, altKey=False, shiftKey=False, metaKey=False, button=None, relatedTarget=None, from_json=None, *args, **kwargs)[source]

Legacy initializer for updating an existing mouse event.

Return type:

MouseEvent

property clientX: Any
property clientY: Any
property altKey: bool
property ctrlKey: bool
property shiftKey: bool
property metaKey: bool
property button: Any
property buttons: Any
property which: int
getModifierState(keyArg)[source]

Return whether the named modifier key was active for the event.

Return type:

bool

class domonic.events.KeyboardEvent(_type, options=None, *args, **kwargs)[source]

Bases: UIEvent

Keyboard input event with normalized key, code, and modifier state.

KEYDOWN: str = 'keydown'
KEYPRESS: str = 'keypress'
KEYUP: str = 'keyup'
DOM_KEY_LOCATION_STANDARD: int = 0
DOM_KEY_LOCATION_LEFT: int = 1
DOM_KEY_LOCATION_RIGHT: int = 2
DOM_KEY_LOCATION_NUMPAD: int = 3
initKeyboardEvent(typeArg, canBubbleArg, cancelableArg, viewArg, charArg, keyArg, locationArg, modifiersListArg, repeat)[source]

Legacy initializer for updating an existing keyboard event.

Return type:

KeyboardEvent

property altKey: bool
property ctrlKey: bool
property shiftKey: bool
property metaKey: bool
property unicode: str
getModifierState(keyArg)[source]

Return whether the named modifier key was active for the event.

Return type:

bool

class domonic.events.CompositionEvent(_type, options=None, *args, **kwargs)[source]

Bases: UIEvent

Input method editor composition event.

START: str = 'compositionstart'
END: str = 'compositionend'
UPDATE: str = 'compositionupdate'
class domonic.events.FocusEvent(_type, options=None, *args, **kwargs)[source]

Bases: UIEvent

Focus transition event with an optional related target.

BLUR: str = 'blur'
FOCUS: str = 'focus'
FOCUSIN: str = 'focusin'
FOCUSOUT: str = 'focusout'
class domonic.events.TouchEvent(_type, options=None, *args, **kwargs)[source]

Bases: UIEvent

Touch input event with active, target, and changed touch lists.

TOUCHCANCEL: str = 'touchcancel'
TOUCHEND: str = 'touchend'
TOUCHMOVE: str = 'touchmove'
TOUCHSTART: str = 'touchstart'
getModifierState(keyArg)[source]

Return whether the named modifier key was active for the event.

Return type:

bool

class domonic.events.WheelEvent(_type, options=None, *args, **kwargs)[source]

Bases: UIEvent

Wheel input event with delta values and delta mode constants.

DOM_DELTA_PIXEL: int = 0
DOM_DELTA_LINE: int = 1
DOM_DELTA_PAGE: int = 2
MOUSEWHEEL: str = 'mousewheel'
WHEEL: str = 'wheel'
class domonic.events.AnimationEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

CSS animation lifecycle event.

ANIMATIONEND: str = 'animationend'
ANIMATIONITERATION: str = 'animationiteration'
ANIMATIONSTART: str = 'animationstart'
class domonic.events.ClipboardEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Clipboard operation event exposing clipboard data.

COPY: str = 'copy'
CUT: str = 'cut'
PASTE: str = 'paste'
class domonic.events.ErrorEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Script or resource error event.

ERROR: str = 'error'
message: str
class domonic.events.CloseEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Close event used by streams, sockets, and similar resources.

CLOSE: str = 'close'
class domonic.events.SubmitEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Form submission event with submitting-control and WebMCP state.

SUBMIT: str = 'submit'
respondWith(response)[source]

Store and return a response supplied for an agent-invoked submit.

Return type:

Any

class domonic.events.ToolEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

WebMCP tool lifecycle event carrying a tool name.

TOOLACTIVATED: str = 'toolactivated'
TOOLCANCEL: str = 'toolcancel'
TOOLCHANGE: str = 'toolchange'
class domonic.events.PointerEvent(_type, options=None, *args, **kwargs)[source]

Bases: MouseEvent

Pointer input event extending mouse events for pen, touch, and mouse.

POINTER: str = 'pointer'
POINTERCANCEL: str = 'pointercancel'
POINTERDOWN: str = 'pointerdown'
POINTERENTER: str = 'pointerenter'
POINTERLEAVE: str = 'pointerleave'
POINTERMOVE: str = 'pointermove'
POINTEROUT: str = 'pointerout'
POINTEROVER: str = 'pointerover'
POINTERUP: str = 'pointerup'
pointerId: float
width: float
height: float
pressure: float
tangentialPressure: float
tiltX: float
tiltY: float
twist: float
altitudeAngle: float
azimuthAngle: float
pointerType: str
isPrimary: bool
persistentDeviceId: int
getCoalescedEvents()[source]

Return the coalesced pointer events supplied at construction.

Return type:

list[Any]

getPredictedEvents()[source]

Return the predicted pointer events supplied at construction.

Return type:

list[Any]

class domonic.events.BeforeUnloadEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Before-unload event with browser-compatible return value handling.

BEFOREUNLOAD: str = 'beforeunload'
property returnValue: Any
class domonic.events.SVGEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

SVG event type constants and base behavior.

ABORT: str = 'abort'
LOAD: str = 'load'
LOADEDDATA: str = 'loadeddata'
LOADEDMETADATA: str = 'loadedmetadata'
LOADSTART: str = 'loadstart'
PROGRESS: str = 'progress'
SCROLL: str = 'scroll'
UNLOAD: str = 'unload'
ERROR: str = 'error'
class domonic.events.TimerEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Timer lifecycle event used by domonic animation helpers.

TIMER: str = 'timer'
TIMER_COMPLETE: str = 'timercomplete'
class domonic.events.DragEvent(_type, options=None, *args, **kwargs)[source]

Bases: MouseEvent

Drag-and-drop event carrying optional data transfer state.

DRAG: str = 'drag'
DRAGEND: str = 'dragend'
DRAGENTER: str = 'dragenter'
DRAGEXIT: str = 'dragexit'
DRAGLEAVE: str = 'dragleave'
DRAGOVER: str = 'dragover'
DRAGSTART: str = 'dragstart'
END: str = 'dragend'
ENTER: str = 'dragenter'
EXIT: str = 'dragexit'
LEAVE: str = 'dragleave'
OVER: str = 'dragover'
START: str = 'dragstart'
DROP: str = 'drop'
class domonic.events.HashChangeEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

URL fragment transition event.

CHANGE: str = 'hashchange'
class domonic.events.InputEvent(_type, options=None, *args, **kwargs)[source]

Bases: UIEvent

Editable-content input event with inserted data and target ranges.

CHANGE: str = 'change'
SELECT: str = 'select'
INPUT: str = 'input'
getTargetRanges()[source]

Return target ranges affected by the insertion or deletion.

Return type:

list[Any]

class domonic.events.PageTransitionEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Page show/hide transition event.

PAGEHIDE: str = 'pagehide'
PAGESHOW: str = 'pageshow'
class domonic.events.PopStateEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

History navigation event carrying restored state.

POPSTATE: str = 'popstate'
class domonic.events.StorageEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Storage mutation event.

STORAGE: str = 'storage'
class domonic.events.TransitionEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

CSS transition lifecycle event.

TRANSITIONEND: str = 'transitionend'
class domonic.events.ProgressEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Progress event with byte counts and computability state.

LOADSTART: str = 'loadstart'
PROGRESS: str = 'progress'
ABORT: str = 'abort'
ERROR: str = 'error'
LOAD: str = 'load'
LOADED: str = 'loaded'
LOADEND: str = 'loadend'
TIMEOUT: str = 'timeout'
lengthComputable: bool
loaded: int
total: int
class domonic.events.CustomEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Custom application event carrying arbitrary detail data.

initCustomEvent(_type, bubbles=True, cancelable=True, detail=None)[source]
Return type:

CustomEvent

class domonic.events.ToggleEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Popover or details toggle event with old and new state.

BEFORETOGGLE: str = 'beforetoggle'
TOGGLE: str = 'toggle'
class domonic.events.CommandEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Command activation event carrying a command string and source.

COMMAND: str = 'command'
class domonic.events.GamePadEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Gamepad connection event.

START: str = 'gamepadconnected'
STOP: str = 'gamepaddisconnected'
class domonic.events.FormDataEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

FormData construction event carrying a form data object.

FORMDATA: str = 'formdata'
class domonic.events.TrackEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Media track add/remove event.

ADDTRACK: str = 'addtrack'
REMOVETRACK: str = 'removetrack'
class domonic.events.BlobEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Media recorder data event carrying a blob-like object.

DATAAVAILABLE: str = 'dataavailable'
class domonic.events.DeviceMotionEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Device motion event with acceleration and rotation readings.

DEVICEMOTION: str = 'devicemotion'
class domonic.events.DeviceOrientationEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Device orientation event with alpha, beta, and gamma angles.

DEVICEORIENTATION: str = 'deviceorientation'
DEVICEORIENTATIONABSOLUTE: str = 'deviceorientationabsolute'
class domonic.events.DeviceLightEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Ambient light event carrying a light level value.

DEVICELIGHT: str = 'devicelight'
class domonic.events.DeviceProximityEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Device proximity event carrying distance bounds.

DEVICEPROXIMITY: str = 'deviceproximity'
class domonic.events.WebGLContextEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

WebGL context lifecycle event with an optional status message.

WEBGLCONTEXTLOST: str = 'webglcontextlost'
WEBGLCONTEXTRESTORED: str = 'webglcontextrestored'
WEBGLCONTEXTCREATIONERROR: str = 'webglcontextcreationerror'
class domonic.events.FetchEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Service-worker-style fetch event.

FETCH: str = 'fetch'
property isReload: bool
property replacesClientId: bool
property resultingClientId: Any
respondWith(response)[source]

Store and return the response object supplied for this fetch.

Return type:

Any

waitUntil(promise)[source]

Track and return a pending wait object supplied by the caller.

Return type:

Any

class domonic.events.ExtendableEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Event that can track caller-supplied work before completion.

waitUntil(promise)[source]

Track and return a pending wait object supplied by the caller.

Return type:

Any

class domonic.events.SyncEvent(_type, options=None, *args, **kwargs)[source]

Bases: ExtendableEvent

Background sync event with tag and final-attempt state.

SYNC: str = 'sync'
class domonic.events.SecurityPolicyViolationEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Content Security Policy violation event.

SECURITY_POLICY_VIOLATION: str = 'securitypolicyviolation'
class domonic.events.DOMContentLoadedEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Document-ready event carrying the loaded document.

DOMCONTENTLOADED: str = 'DOMContentLoaded'
class domonic.events.TweenEvent(_type, source=None, bubbles=False, cancelable=False)[source]

Bases: Event

Animation tween lifecycle event with a source object.

START: str = 'onStart'
STOP: str = 'onStop'
RESET: str = 'onReset'
PAUSE: str = 'onPause'
UNPAUSE: str = 'onUnPause'
UPDATE_START: str = 'onUpdateStart'
UPDATE_END: str = 'onUpdateEnd'
COMPLETE: str = 'onComplete'
TIMER: str = 'onTimer'
property source: Any
class domonic.events.PromiseRejectionEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Unhandled or handled promise rejection event.

UNHANDLED: str = 'unhandledrejection'
HANDLED: str = 'rejectionhandled'
class domonic.events.MessageEvent(_type, options=None, *args, **kwargs)[source]

Bases: Event

Cross-context message event.

MESSAGE: str = 'message'
CONNECT: str = 'connect'
DISCONNECT: str = 'disconnect'
class domonic.events.GlobalEventHandler[source]

Bases: object

Mixin that installs default on* event handler methods.

onabort(event)
Return type:

Any

onanimationcancel(event)
Return type:

Any

onanimationend(event)
Return type:

Any

onanimationiteration(event)
Return type:

Any

onauxclick(event)
Return type:

Any

onbeforeinput(event)
Return type:

Any

onbeforematch(event)
Return type:

Any

onbeforetoggle(event)
Return type:

Any

onblur(event)
Return type:

Any

oncancel(event)
Return type:

Any

oncanplay(event)
Return type:

Any

oncanplaythrough(event)
Return type:

Any

onchange(event)
Return type:

Any

onclick(event)
Return type:

Any

onclose(event)
Return type:

Any

oncommand(event)
Return type:

Any

onconnect(event)
Return type:

Any

oncontextlost(event)
Return type:

Any

oncontextmenu(event)
Return type:

Any

oncontextrestored(event)
Return type:

Any

oncuechange(event)
Return type:

Any

oncurrententrychange(event)
Return type:

Any

ondblclick(event)
Return type:

Any

ondispose(event)
Return type:

Any

ondrag(event)
Return type:

Any

ondragend(event)
Return type:

Any

ondragenter(event)
Return type:

Any

ondragexit(event)
Return type:

Any

ondragleave(event)
Return type:

Any

ondragover(event)
Return type:

Any

ondragstart(event)
Return type:

Any

ondrop(event)
Return type:

Any

ondurationchange(event)
Return type:

Any

onemptied(event)
Return type:

Any

onended(event)
Return type:

Any

onerror(event)
Return type:

Any

onfocus(event)
Return type:

Any

onformdata(event)
Return type:

Any

ongotpointercapture(event)
Return type:

Any

oninput(event)
Return type:

Any

oninvalid(event)
Return type:

Any

onkeydown(event)
Return type:

Any

onkeypress(event)
Return type:

Any

onkeyup(event)
Return type:

Any

onlanguagechange(event)
Return type:

Any

onload(event)
Return type:

Any

onloadeddata(event)
Return type:

Any

onloadedmetadata(event)
Return type:

Any

onloadend(event)
Return type:

Any

onloadstart(event)
Return type:

Any

onlostpointercapture(event)
Return type:

Any

onmessage(event)
Return type:

Any

onmessageerror(event)
Return type:

Any

onmousedown(event)
Return type:

Any

onmouseenter(event)
Return type:

Any

onmouseleave(event)
Return type:

Any

onmousemove(event)
Return type:

Any

onmouseout(event)
Return type:

Any

onmouseover(event)
Return type:

Any

onmouseup(event)
Return type:

Any

onnavigate(event)
Return type:

Any

onnavigateerror(event)
Return type:

Any

onnavigatesuccess(event)
Return type:

Any

onopen(event)
Return type:

Any

onpause(event)
Return type:

Any

onplay(event)
Return type:

Any

onplaying(event)
Return type:

Any

onpointercancel(event)
Return type:

Any

onpointerdown(event)
Return type:

Any

onpointerenter(event)
Return type:

Any

onpointerleave(event)
Return type:

Any

onpointermove(event)
Return type:

Any

onpointerout(event)
Return type:

Any

onpointerover(event)
Return type:

Any

onpointerup(event)
Return type:

Any

onprogress(event)
Return type:

Any

onratechange(event)
Return type:

Any

onreadystatechange(event)
Return type:

Any

onrejectionhandled(event)
Return type:

Any

onreset(event)
Return type:

Any

onresize(event)
Return type:

Any

onscroll(event)
Return type:

Any

onscrollend(event)
Return type:

Any

onsearch(event)
Return type:

Any

onsecuritypolicyviolation(event)
Return type:

Any

onseeked(event)
Return type:

Any

onseeking(event)
Return type:

Any

onselect(event)
Return type:

Any

onselectionchange(event)
Return type:

Any

onselectstart(event)
Return type:

Any

onshow(event)
Return type:

Any

onslotchange(event)
Return type:

Any

onstalled(event)
Return type:

Any

onsubmit(event)
Return type:

Any

onsuspend(event)
Return type:

Any

ontimeupdate(event)
Return type:

Any

ontoggle(event)
Return type:

Any

ontoolactivated(event)
Return type:

Any

ontoolcancel(event)
Return type:

Any

ontoolchange(event)
Return type:

Any

ontouchcancel(event)
Return type:

Any

ontouchstart(event)
Return type:

Any

ontransitioncancel(event)
Return type:

Any

ontransitionend(event)
Return type:

Any

onunhandledrejection(event)
Return type:

Any

onvisibilitychange(event)
Return type:

Any

onvolumechange(event)
Return type:

Any

onwaiting(event)
Return type:

Any

onwheel(event)
Return type:

Any

class domonic.events.WindowEventHandler(window)[source]

Bases: object

Window-specific on* event handler methods.

onabort(event)
Return type:

Any

onafterprint(event)
Return type:

Any

onbeforeinput(event)
Return type:

Any

onbeforematch(event)
Return type:

Any

onbeforeprint(event)
Return type:

Any

onbeforetoggle(event)
Return type:

Any

onbeforeunload(event)
Return type:

Any

onblur(event)
Return type:

Any

oncanplay(event)
Return type:

Any

oncanplaythrough(event)
Return type:

Any

onchange(event)
Return type:

Any

onclick(event)
Return type:

Any

oncommand(event)
Return type:

Any

onconnect(event)
Return type:

Any

oncontextlost(event)
Return type:

Any

oncontextmenu(event)
Return type:

Any

oncontextrestored(event)
Return type:

Any

oncopy(event)
Return type:

Any

oncuechange(event)
Return type:

Any

oncurrententrychange(event)
Return type:

Any

oncut(event)
Return type:

Any

ondblclick(event)
Return type:

Any

ondispose(event)
Return type:

Any

ondrag(event)
Return type:

Any

ondragend(event)
Return type:

Any

ondragenter(event)
Return type:

Any

ondragleave(event)
Return type:

Any

ondragover(event)
Return type:

Any

ondragstart(event)
Return type:

Any

ondrop(event)
Return type:

Any

ondurationchange(event)
Return type:

Any

onemptied(event)
Return type:

Any

onended(event)
Return type:

Any

onerror(event)
Return type:

Any

onfocus(event)
Return type:

Any

onformdata(event)
Return type:

Any

onhashchange(event)
Return type:

Any

oninput(event)
Return type:

Any

oninvalid(event)
Return type:

Any

onkeydown(event)
Return type:

Any

onkeypress(event)
Return type:

Any

onkeyup(event)
Return type:

Any

onlanguagechange(event)
Return type:

Any

onload(event)
Return type:

Any

onloadeddata(event)
Return type:

Any

onloadedmetadata(event)
Return type:

Any

onloadstart(event)
Return type:

Any

onmessage(event)
Return type:

Any

onmessageerror(event)
Return type:

Any

onmousedown(event)
Return type:

Any

onmouseenter(event)
Return type:

Any

onmouseleave(event)
Return type:

Any

onmousemove(event)
Return type:

Any

onmouseout(event)
Return type:

Any

onmouseover(event)
Return type:

Any

onmouseup(event)
Return type:

Any

onmousewheel(event)
Return type:

Any

onnavigate(event)
Return type:

Any

onnavigateerror(event)
Return type:

Any

onnavigatesuccess(event)
Return type:

Any

onoffline(event)
Return type:

Any

ononline(event)
Return type:

Any

onopen(event)
Return type:

Any

onpagehide(event)
Return type:

Any

onpagereveal(event)
Return type:

Any

onpageshow(event)
Return type:

Any

onpageswap(event)
Return type:

Any

onpaste(event)
Return type:

Any

onpopstate(event)
Return type:

Any

onreadystatechange(event)
Return type:

Any

onrejectionhandled(event)
Return type:

Any

onresize(event)
Return type:

Any

onscroll(event)
Return type:

Any

onscrollend(event)
Return type:

Any

onsearch(event)
Return type:

Any

onsecuritypolicyviolation(event)
Return type:

Any

onslotchange(event)
Return type:

Any

onstorage(event)
Return type:

Any

onsubmit(event)
Return type:

Any

ontoggle(event)
Return type:

Any

ontoolactivated(event)
Return type:

Any

ontoolcancel(event)
Return type:

Any

ontoolchange(event)
Return type:

Any

onunhandledrejection(event)
Return type:

Any

onunload(event)
Return type:

Any

onvisibilitychange(event)
Return type:

Any