Document Class
The Document class provides comprehensive methods for interacting with the Document Object Model (DOM). It's available as ui.document
in your main function and represents the HTML document loaded in the browser.
Overview
The Document object is the main entry point for DOM manipulation in PyPositron. It allows you to:
- Select elements using various methods
- Create new elements
- Manipulate document properties
- Handle document-level events
- Access document metadata
Properties
Document Information
activeElement -> Element
: Returns the currently focused element in the document. W3Schools Reference | MDN ReferencebaseURI -> str
: Returns the absolute base URI of a document. W3Schools Reference | MDN ReferencecharacterSet -> str
: Returns the character encoding for the document. W3Schools Reference | MDN Referencedoctype
: Returns the Document Type Declaration associated with the document. W3Schools Reference | MDN ReferencedocumentElement -> Element
: Returns the Document Element of the document (the<html>
element). W3Schools Reference | MDN ReferencedocumentURI -> str
: Returns the location of the document. W3Schools Reference | MDN Referencedomain -> str
: Returns the domain name of the server that loaded the document. W3Schools Reference | MDN ReferencelastModified -> str
: Returns the date and time the document was last modified. W3Schools Reference | MDN ReferencereadyState -> str
: Returns the (loading) status of the document. W3Schools Reference | MDN Referencereferrer -> str
: Returns the URL of the document that loaded the current document. W3Schools Reference | MDN Referencetitle -> str
: Gets or sets the title of the document. W3Schools Reference | MDN ReferenceURL -> str
: Returns the full URL of the HTML document. W3Schools Reference | MDN Reference
Document Structure
body -> Element
: Gets the document body element. W3Schools Reference | MDN Referencehead -> Element
: Returns the<head>
element of the document. W3Schools Reference | MDN Referencehtml -> Element
: Gets the document html element. W3Schools Reference | MDN Reference
Element Collections
embeds -> ElementList
: Returns a collection of all<embed>
elements in the document. W3Schools Reference | MDN Referenceforms -> ElementList
: Gets all the forms in the document. W3Schools Reference | MDN Referenceimages -> ElementList
: Returns a collection of all<img>
elements in the document. W3Schools Reference | MDN Referencelinks -> ElementList
: Returns a collection of all<a>
and<area>
elements in the document that have a href attribute. W3Schools Reference | MDN Referencescripts -> ElementList
: Returns a collection of<script>
elements in the document. W3Schools Reference | MDN Reference
Browser-specific Properties
cookie -> str
: Gets or sets all name/value pairs of cookies in the document. W3Schools Reference | MDN ReferencedefaultView
: Returns the window object associated with a document, or null if none is available. W3Schools Reference | MDN ReferencedesignMode -> str
: Controls whether the entire document should be editable or not. W3Schools Reference | MDN Referenceimplementation
: Returns the DOMImplementation object that handles this document. W3Schools Reference | MDN Reference
Methods
Element Selection
getElementById(element_id: str) -> Element
: Gets element by ID. This is the most common way to select elements. W3Schools Reference | MDN ReferencegetElementsByClassName(class_name: str) -> ElementList
: Gets elements by class name. Returns all elements with the specified class. W3Schools Reference | MDN ReferencegetElementsByTagName(tag_name: str) -> ElementList
: Returns an HTMLCollection containing all elements with the specified tag name. W3Schools Reference | MDN ReferencegetElementsByName(name: str) -> ElementList
: Returns a live NodeList containing all elements with the specified name. W3Schools Reference | MDN ReferencequerySelector(selector: str) -> Element
: Gets first element matching CSS selector. Very powerful for complex selections. W3Schools Reference | MDN ReferencequerySelectorAll(selector: str) -> ElementList
: Gets all elements matching CSS selector. W3Schools Reference | MDN Reference
Element Creation
createElement(tag_name: str) -> Element
: Creates a new element with the specified tag name. W3Schools Reference | MDN ReferencecreateTextNode(text: str)
: Creates a Text node. W3Schools Reference | MDN ReferencecreateComment(text: str)
: Creates a Comment node with the specified text. W3Schools Reference | MDN ReferencecreateDocumentFragment()
: Creates an empty DocumentFragment node. W3Schools Reference | MDN ReferencecreateAttribute(name: str)
: Creates an attribute node. W3Schools Reference | MDN Reference
Event Handling
addEventListener(event_type: str, callback: Callable) -> bool
: Attaches an event handler to the document. W3Schools Reference | MDN ReferenceremoveEventListener(event_type: str, callback=None)
: Removes an event handler from the document. W3Schools Reference | MDN ReferencecreateEvent(event_type: str)
: Creates a new event. W3Schools Reference | MDN Reference
Document State
hasFocus() -> bool
: Returns a Boolean value indicating whether the document has focus. W3Schools Reference | MDN Referencenormalize()
: Removes empty Text nodes, and joins adjacent nodes. W3Schools Reference | MDN Reference
Document Manipulation
adoptNode(node)
: Adopts a node from another document. W3Schools Reference | MDN ReferenceimportNode(node, deep: bool = False)
: Imports a node from another document. W3Schools Reference | MDN Reference
Document Output
write(*args)
: Writes HTML expressions or JavaScript code to a document. W3Schools Reference | MDN Referencewriteln(*args)
: Same as write(), but adds a newline character after each statement. W3Schools Reference | MDN Referenceopen(mime_type: str | None = None, replace: str | None = None)
: Opens an HTML output stream to collect output from document.write(). W3Schools Reference | MDN Referenceclose()
: Closes the output stream previously opened with document.open(). W3Schools Reference | MDN Reference
Dialog Methods
alert(message: str)
: Shows an alert pop-up dialog.confirm(message: str) -> bool
: Shows a confirm dialog with "Yes" and "No" buttons, returns True or False.prompt(message: str, default_value: str = None) -> str
: Shows a prompt dialog with an input field, returns the input value or None if cancelled.
PyPositron-specific Methods
switchView(path: str) -> bool
: Switches to another HTML view and re-executes its<py>
tags. PyPositron-specific method.
Usage Examples
Basic Element Selection
def main(ui):
# Get single elements
title = ui.document.getElementById("pageTitle")
first_button = ui.document.querySelector(".btn")
# Get multiple elements
all_buttons = ui.document.getElementsByClassName("btn")
all_paragraphs = ui.document.getElementsByTagName("p")
form_inputs = ui.document.querySelectorAll("form input")
Element Creation and Manipulation
def main(ui):
# Create new elements
new_div = ui.document.createElement("div")
new_div.innerText = "Hello World!"
new_div.style.color = "blue"
# Add to document
ui.document.body.appendChild(new_div)
# Set document properties
ui.document.title = "My PyPositron App"
Event Handling
def main(ui):
def on_document_ready():
print("Document is ready!")
def on_key_press():
print("Key was pressed!")
# Add document-level event listeners
ui.document.addEventListener("DOMContentLoaded", on_document_ready)
ui.document.addEventListener("keydown", on_key_press)
Form Handling
def main(ui):
# Get all forms in the document
forms = ui.document.forms
for form in forms:
def handle_submit():
print("Form submitted!")
return False # Prevent default submission
form.addEventListener("submit", handle_submit)
Working with Collections
def main(ui):
# Get all images and set alt text
images = ui.document.images
for i, img in enumerate(images):
img.setAttribute("alt", f"Image {i+1}")
# Get all links and add target="_blank"
links = ui.document.links
for link in links:
link.setAttribute("target", "_blank")
Best Practices
-
Use specific selectors: Prefer
getElementById()
when you have an ID, as it's the fastest method. -
Cache element references: Store frequently accessed elements in variables rather than selecting them repeatedly.
-
Use CSS selectors effectively:
querySelector()
andquerySelectorAll()
are very powerful - learn CSS selectors to make the most of them. -
Handle events at the document level: For events that need to work on dynamically created elements, consider using document-level event listeners.
-
Check element existence: Always verify that elements exist before manipulating them.
def main(ui):
button = ui.document.getElementById("myButton")
if button: # Check if element exists
button.addEventListener("click", my_handler)
Related Classes
- Element: Individual DOM elements returned by Document methods
- ElementList: Collections of elements returned by methods like
getElementsByClassName
- Style: CSS styling for elements
- HTMLWindow: Browser window functionality