PyPositron Docs

Element Class

The Element class represents a single DOM element in the HTML document. Elements are returned by document query methods like getElementById(), querySelector(), and created by createElement(). This class provides comprehensive access to all element properties and methods available in the DOM.

Overview

The Element class is the foundation of DOM manipulation in PyPositron. Every HTML element becomes an Element object that you can:

  • Read and modify properties (text, attributes, styling)
  • Handle events (clicks, form input, etc.)
  • Navigate the DOM tree (parents, children, siblings)
  • Manipulate the element's position and appearance

Properties

Basic Element Information

Content Properties

Accessibility and User Interaction

Dimensions and Position

Scroll Properties

DOM Tree Navigation

Node Information

Styling

Methods

Event Handling

  • addEventListener(event_type: str, callback: Callable) -> bool: Adds an event listener to the element. Returns True if successful. W3Schools Reference | MDN Reference
  • removeEventListener(event_type: str, callback=None): Removes an event handler that has been attached with the addEventListener() method. W3Schools Reference | MDN Reference

Focus and Interaction

Attribute Manipulation

DOM Tree Manipulation

Modern DOM Manipulation

  • append(*nodes): Adds (appends) one or several nodes (element) or strings after the last child of an element. W3Schools Reference | MDN Reference
  • after(*nodes): Inserts one or more nodes (elements) or strings after an element. W3Schools Reference | MDN Reference
  • before(*nodes): Inserts one or more nodes (elements) or strings before an element. W3Schools Reference | MDN Reference
  • insertAdjacentElement(position: str, element: Element) -> Element: Inserts a new HTML element at a position relative to an element. Position values: "beforebegin", "afterbegin", "beforeend", "afterend". W3Schools Reference | MDN Reference
  • insertAdjacentHTML(position: str, html: str): Inserts an HTML formatted text at a position relative to an element. Position values: "beforebegin", "afterbegin", "beforeend", "afterend". W3Schools Reference | MDN Reference
  • insertAdjacentText(position: str, text: str): Inserts text into a position relative to an element. Position values: "beforebegin", "afterbegin", "beforeend", "afterend". W3Schools Reference | MDN Reference

Element Query Methods

Element Information

Element Comparison and Testing

Utility Methods

Common Event Types for addEventListener

Mouse Events

(W3Schools Reference | MDN Reference)

  • "click": Triggered when an element is clicked
  • "dblclick": Triggered when an element is double-clicked
  • "mousedown": Triggered when a mouse button is pressed down
  • "mouseup": Triggered when a mouse button is released
  • "mouseover": Triggered when the mouse pointer moves over an element
  • "mouseout": Triggered when the mouse pointer leaves an element
  • "mouseenter": Triggered when the mouse pointer enters an element
  • "mouseleave": Triggered when the mouse pointer leaves an element
  • "mousemove": Triggered when the mouse pointer moves within an element

Keyboard Events

(W3Schools Reference | MDN Reference)

  • "keydown": Triggered when a key is pressed down
  • "keyup": Triggered when a key is released
  • "keypress": Triggered when a key is pressed (deprecated, use keydown/keyup instead)

Form Events

(W3Schools Reference | MDN Reference)

  • "change": Triggered when the value of a form element changes
  • "input": Triggered when the value of an input element changes
  • "submit": Triggered when a form is submitted
  • "reset": Triggered when a form is reset
  • "focus": Triggered when an element gains focus
  • "blur": Triggered when an element loses focus
  • "focusin": Triggered when an element is about to receive focus
  • "focusout": Triggered when an element is about to lose focus

Touch Events (for mobile devices)

(W3Schools Reference | MDN Reference)

  • "touchstart": Triggered when a touch point is placed on the touch surface
  • "touchend": Triggered when a touch point is removed from the touch surface
  • "touchmove": Triggered when a touch point is moved along the touch surface
  • "touchcancel": Triggered when a touch point has been disrupted

Drag and Drop Events

(W3Schools Reference | MDN Reference)

  • "drag": Triggered when an element is being dragged
  • "dragstart": Triggered when drag operation starts
  • "dragend": Triggered when drag operation ends
  • "dragover": Triggered when dragged element is over a drop target
  • "dragenter": Triggered when dragged element enters a drop target
  • "dragleave": Triggered when dragged element leaves a drop target
  • "drop": Triggered when dragged element is dropped

Usage Examples

Basic Element Manipulation

def main(ui):
    # Get an element
    button = ui.document.getElementById("myButton")
    
    # Modify content
    button.innerText = "Click Me!"
    button.setAttribute("disabled", "false")
    
    # Styling
    button.style.backgroundColor = "blue"
    button.style.color = "white"
    button.style.padding = "10px 20px"
    
    # Add event handler
    def handle_click():
        button.innerText = "Clicked!"
        button.style.backgroundColor = "green"
    
    button.addEventListener("click", handle_click)

Form Handling

def main(ui):
    # Get form elements
    name_input = ui.document.getElementById("nameInput")
    email_input = ui.document.getElementById("emailInput")
    submit_btn = ui.document.getElementById("submitBtn")
    
    def validate_form():
        name = name_input.value.strip()
        email = email_input.value.strip()
        
        # Enable/disable submit button based on validation
        if name and "@" in email:
            submit_btn.removeAttribute("disabled")
            submit_btn.style.opacity = "1"
        else:
            submit_btn.setAttribute("disabled", "true")
            submit_btn.style.opacity = "0.5"
    
    # Add input event listeners for real-time validation
    name_input.addEventListener("input", validate_form)
    email_input.addEventListener("input", validate_form)
    
    # Initial validation
    validate_form()

Dynamic Content Creation

def main(ui):
    container = ui.document.getElementById("container")
    
    def add_item(text):
        # Create new elements
        item = ui.document.createElement("div")
        item.className = "list-item"
        item.innerText = text
        
        # Add remove button
        remove_btn = ui.document.createElement("button")
        remove_btn.innerText = "Remove"
        remove_btn.style.marginLeft = "10px"
        
        def remove_item():
            item.remove()
        
        remove_btn.addEventListener("click", remove_item)
        
        # Assemble and add to container
        item.appendChild(remove_btn)
        container.appendChild(item)
    
    # Add some initial items
    add_item("First item")
    add_item("Second item")
    add_item("Third item")

DOM Tree Navigation

def main(ui):
    def highlight_siblings(element):
        # Get parent and iterate through siblings
        parent = element.parentElement
        if parent:
            children = parent.children
            for i in range(len(children)):
                child = children[i]
                if child != element:
                    child.style.backgroundColor = "yellow"
                else:
                    child.style.backgroundColor = "lightblue"
    
    # Add click handlers to all buttons
    buttons = ui.document.getElementsByTagName("button")
    for button in buttons:
        button.addEventListener("click", lambda: highlight_siblings(button))

Advanced Event Handling

def main(ui):
    # Multi-event handling
    input_field = ui.document.getElementById("searchInput")
    search_results = ui.document.getElementById("searchResults")
    
    def handle_focus():
        input_field.style.borderColor = "blue"
        input_field.style.boxShadow = "0 0 5px rgba(0,0,255,0.3)"
    
    def handle_blur():
        input_field.style.borderColor = ""
        input_field.style.boxShadow = ""
    
    def handle_input():
        query = input_field.value
        if len(query) > 2:
            # Simulate search results
            search_results.innerHTML = f"<p>Searching for: {query}</p>"
        else:
            search_results.innerHTML = ""
    
    def handle_keydown(event):
        # You can access event information if needed
        if input_field.value == "" and len(input_field.value) == 0:
            search_results.innerHTML = "<p>Start typing to search...</p>"
    
    # Add multiple event listeners
    input_field.addEventListener("focus", handle_focus)
    input_field.addEventListener("blur", handle_blur)
    input_field.addEventListener("input", handle_input)
    input_field.addEventListener("keydown", handle_keydown)

Best Practices

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

  2. Use specific selectors: When possible, use getElementById() as it's the fastest selection method.

  3. Check element existence: Always verify that elements exist before manipulating them.

  4. Use appropriate content properties:

    • Use innerText for plain text content
    • Use innerHTML only when you need to insert HTML (and ensure it's safe)
    • Use textContent for cross-browser compatibility
  5. Handle events efficiently: Remove event listeners when they're no longer needed to prevent memory leaks.

  6. Use modern DOM methods: Prefer append(), before(), after() over older methods when possible.

  7. Validate form inputs: Always validate user input both in real-time and before submission.

Related Classes

  • Document: The document object that contains elements
  • ElementList: Collections of elements returned by query methods
  • Style: CSS styling interface for elements
  • HTMLWindow: Browser window functionality