PyPositron Docs

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

Document Structure

Element Collections

Browser-specific Properties

Methods

Element Selection

Element Creation

Event Handling

Document State

Document Manipulation

Document Output

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

  1. Use specific selectors: Prefer getElementById() when you have an ID, as it's the fastest method.

  2. Cache element references: Store frequently accessed elements in variables rather than selecting them repeatedly.

  3. Use CSS selectors effectively: querySelector() and querySelectorAll() are very powerful - learn CSS selectors to make the most of them.

  4. Handle events at the document level: For events that need to work on dynamically created elements, consider using document-level event listeners.

  5. 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