-
Notifications
You must be signed in to change notification settings - Fork 2
Document
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.
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
-
activeElement -> Element
: Returns the currently focused element in the document. W3Schools Reference | MDN Reference -
baseURI -> str
: Returns the absolute base URI of a document. W3Schools Reference | MDN Reference -
characterSet -> str
: Returns the character encoding for the document. W3Schools Reference | MDN Reference -
doctype
: Returns the Document Type Declaration associated with the document. W3Schools Reference | MDN Reference -
documentElement -> Element
: Returns the Document Element of the document (the<html>
element). W3Schools Reference | MDN Reference -
documentURI -> str
: Returns the location of the document. W3Schools Reference | MDN Reference -
domain -> str
: Returns the domain name of the server that loaded the document. W3Schools Reference | MDN Reference -
lastModified -> str
: Returns the date and time the document was last modified. W3Schools Reference | MDN Reference -
readyState -> str
: Returns the (loading) status of the document. W3Schools Reference | MDN Reference -
referrer -> str
: Returns the URL of the document that loaded the current document. W3Schools Reference | MDN Reference -
title -> str
: Gets or sets the title of the document. W3Schools Reference | MDN Reference -
URL -> str
: Returns the full URL of the HTML document. W3Schools Reference | MDN Reference
-
body -> Element
: Gets the document body element. W3Schools Reference | MDN Reference -
head -> Element
: Returns the<head>
element of the document. W3Schools Reference | MDN Reference -
html -> Element
: Gets the document html element. W3Schools Reference | MDN Reference
-
embeds -> ElementList
: Returns a collection of all<embed>
elements in the document. W3Schools Reference | MDN Reference -
forms -> ElementList
: Gets all the forms in the document. W3Schools Reference | MDN Reference -
images -> ElementList
: Returns a collection of all<img>
elements in the document. W3Schools Reference | MDN Reference -
links -> ElementList
: Returns a collection of all<a>
and<area>
elements in the document that have a href attribute. W3Schools Reference | MDN Reference -
scripts -> ElementList
: Returns a collection of<script>
elements in the document. W3Schools Reference | MDN Reference
-
cookie -> str
: Gets or sets all name/value pairs of cookies in the document. W3Schools Reference | MDN Reference -
defaultView
: Returns the window object associated with a document, or null if none is available. W3Schools Reference | MDN Reference -
designMode -> str
: Controls whether the entire document should be editable or not. W3Schools Reference | MDN Reference -
implementation
: Returns the DOMImplementation object that handles this document. W3Schools Reference | MDN Reference
-
getElementById(element_id: str) -> Element
: Gets element by ID. This is the most common way to select elements. W3Schools Reference | MDN Reference -
getElementsByClassName(class_name: str) -> ElementList
: Gets elements by class name. Returns all elements with the specified class. W3Schools Reference | MDN Reference -
getElementsByTagName(tag_name: str) -> ElementList
: Returns an HTMLCollection containing all elements with the specified tag name. W3Schools Reference | MDN Reference -
getElementsByName(name: str) -> ElementList
: Returns a live NodeList containing all elements with the specified name. W3Schools Reference | MDN Reference -
querySelector(selector: str) -> Element
: Gets first element matching CSS selector. Very powerful for complex selections. W3Schools Reference | MDN Reference -
querySelectorAll(selector: str) -> ElementList
: Gets all elements matching CSS selector. W3Schools Reference | MDN Reference
-
createElement(tag_name: str) -> Element
: Creates a new element with the specified tag name. W3Schools Reference | MDN Reference -
createTextNode(text: str)
: Creates a Text node. W3Schools Reference | MDN Reference -
createComment(text: str)
: Creates a Comment node with the specified text. W3Schools Reference | MDN Reference -
createDocumentFragment()
: Creates an empty DocumentFragment node. W3Schools Reference | MDN Reference -
createAttribute(name: str)
: Creates an attribute node. W3Schools Reference | MDN Reference
-
addEventListener(event_type: str, callback: Callable) -> bool
: Attaches an event handler to the document. W3Schools Reference | MDN Reference -
removeEventListener(event_type: str, callback=None)
: Removes an event handler from the document. W3Schools Reference | MDN Reference -
createEvent(event_type: str)
: Creates a new event. W3Schools Reference | MDN Reference
-
hasFocus() -> bool
: Returns a Boolean value indicating whether the document has focus. W3Schools Reference | MDN Reference -
normalize()
: Removes empty Text nodes, and joins adjacent nodes. W3Schools Reference | MDN Reference
-
adoptNode(node)
: Adopts a node from another document. W3Schools Reference | MDN Reference -
importNode(node, deep: bool = False)
: Imports a node from another document. W3Schools Reference | MDN Reference
-
write(*args)
: Writes HTML expressions or JavaScript code to a document. W3Schools Reference | MDN Reference -
writeln(*args)
: Same as write(), but adds a newline character after each statement. W3Schools Reference | MDN Reference -
open(mime_type: str | None = None, replace: str | None = None)
: Opens an HTML output stream to collect output from document.write(). W3Schools Reference | MDN Reference -
close()
: Closes the output stream previously opened with document.open(). W3Schools Reference | MDN Reference
-
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.
-
switchView(path: str) -> bool
: Switches to another HTML view and re-executes its<py>
tags. PyPositron-specific method.
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")
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"
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)
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)
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")
-
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)
- 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