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
id -> str
: Sets or returns the value of the id attribute of an element. W3Schools Reference | MDN ReferencetagName -> str
: Returns the tag name of an element (e.g., "DIV", "P", "BUTTON"). W3Schools Reference | MDN ReferenceclassName -> str
: Sets or returns the value of the class attribute of an element. W3Schools Reference | MDN ReferenceclassList
: Returns the class name(s) of an element as a DOMTokenList. W3Schools Reference | MDN Referenceattributes
: Returns a NamedNodeMap of an element's attributes. W3Schools Reference | MDN Reference
Content Properties
innerText -> str
: Gets or sets the inner text of the element (text content only, no HTML). W3Schools Reference | MDN ReferenceinnerHTML -> str
: Gets or sets the inner HTML of the element. Warning: This can lead to XSS vulnerabilities if not sanitized properly. W3Schools Reference | MDN ReferencetextContent -> str
: Sets or returns the textual content of a node and its descendants (similar to innerText but with some differences). W3Schools Reference | MDN ReferenceouterHTML -> str
: Sets or returns the content of an element (including the start tag and the end tag). W3Schools Reference | MDN ReferenceouterText -> str
: Sets or returns the outer text content of a node and its descendants. W3Schools Reference | MDN Referencevalue
: Gets or sets the value of a form element (input, textarea, select, etc.). W3Schools Reference | MDN Reference
Accessibility and User Interaction
accessKey -> str
: Sets or returns the accesskey attribute of an element. W3Schools Reference | MDN ReferencecontentEditable -> str
: Sets or returns whether the content of an element is editable or not. W3Schools Reference | MDN ReferenceisContentEditable -> bool
: Returns true if an element's content is editable. W3Schools Reference | MDN ReferencetabIndex -> int
: Sets or returns the value of the tabindex attribute of an element. W3Schools Reference | MDN Referencetitle -> str
: Sets or returns the value of the title attribute of an element (tooltip text). W3Schools Reference | MDN Referencedir -> str
: Sets or returns the value of the dir attribute of an element (text direction). W3Schools Reference | MDN Referencelang -> str
: Sets or returns the value of the lang attribute of an element. W3Schools Reference | MDN Reference
Dimensions and Position
clientHeight -> int
: Returns the height of an element, including padding but excluding border, scrollbar, and margin. W3Schools Reference | MDN ReferenceclientWidth -> int
: Returns the width of an element, including padding but excluding border, scrollbar, and margin. W3Schools Reference | MDN ReferenceclientLeft -> int
: Returns the width of the left border of an element. W3Schools Reference | MDN ReferenceclientTop -> int
: Returns the width of the top border of an element. W3Schools Reference | MDN ReferenceoffsetHeight -> int
: Returns the height of an element, including padding, border and scrollbar. W3Schools Reference | MDN ReferenceoffsetWidth -> int
: Returns the width of an element, including padding, border and scrollbar. W3Schools Reference | MDN ReferenceoffsetLeft -> int
: Returns the horizontal offset position of an element relative to its offset parent. W3Schools Reference | MDN ReferenceoffsetTop -> int
: Returns the vertical offset position of an element relative to its offset parent. W3Schools Reference | MDN ReferenceoffsetParent
: Returns the offset container of an element. W3Schools Reference | MDN Reference
Scroll Properties
scrollHeight -> int
: Returns the entire height of an element, including padding. W3Schools Reference | MDN ReferencescrollWidth -> int
: Returns the entire width of an element, including padding. W3Schools Reference | MDN ReferencescrollLeft -> int
: Sets or returns the number of pixels an element's content is scrolled horizontally. W3Schools Reference | MDN ReferencescrollTop -> int
: Sets or returns the number of pixels an element's content is scrolled vertically. W3Schools Reference | MDN Reference
DOM Tree Navigation
parentNode
: Returns the parent node of an element. W3Schools Reference | MDN ReferenceparentElement
: Returns the parent element node of an element. W3Schools Reference | MDN ReferencechildNodes
: Returns a NodeList of an element's child nodes (includes text nodes). W3Schools Reference | MDN Referencechildren
: Returns an HTMLCollection of an element's child elements (elements only, no text nodes). W3Schools Reference | MDN ReferencechildElementCount -> int
: Returns an element's number of child elements. W3Schools Reference | MDN ReferencefirstChild
: Returns the first child node of an element. W3Schools Reference | MDN ReferencefirstElementChild
: Returns the first child element of an element. W3Schools Reference | MDN ReferencelastChild
: Returns the last child node of an element. W3Schools Reference | MDN ReferencelastElementChild
: Returns the last child element of an element. W3Schools Reference | MDN ReferencenextSibling
: Returns the next node at the same node tree level. W3Schools Reference | MDN ReferencenextElementSibling
: Returns the next element at the same node tree level. W3Schools Reference | MDN ReferencepreviousSibling
: Returns the previous node at the same node tree level. W3Schools Reference | MDN ReferencepreviousElementSibling
: Returns the previous element at the same node tree level. W3Schools Reference | MDN Reference
Node Information
nodeName -> str
: Returns the name of a node (usually the tag name for elements). W3Schools Reference | MDN ReferencenodeType -> int
: Returns the node type of a node (1 for elements). W3Schools Reference | MDN ReferencenodeValue -> str
: Sets or returns the value of a node (null for elements). W3Schools Reference | MDN ReferenceownerDocument
: Returns the root element (document object) for an element. W3Schools Reference | MDN ReferencenamespaceURI -> str
: Returns the namespace URI of an element. W3Schools Reference | MDN Reference
Styling
style -> Style
: Gets the style object of the element for CSS manipulation. W3Schools Reference | MDN Reference
Methods
Event Handling
addEventListener(event_type: str, callback: Callable) -> bool
: Adds an event listener to the element. Returns True if successful. W3Schools Reference | MDN ReferenceremoveEventListener(event_type: str, callback=None)
: Removes an event handler that has been attached with the addEventListener() method. W3Schools Reference | MDN Reference
Focus and Interaction
focus()
: Gives focus to an element. W3Schools Reference | MDN Referenceblur()
: Removes focus from an element. W3Schools Reference | MDN Referenceclick()
: Simulates a mouse-click on an element. W3Schools Reference | MDN Reference
Attribute Manipulation
getAttribute(name: str) -> str
: Returns the value of an element's attribute. W3Schools Reference | MDN ReferencesetAttribute(attr_name: str, value: str)
: Sets an attribute on the element. W3Schools Reference | MDN ReferenceremoveAttribute(name: str)
: Removes an attribute from an element. W3Schools Reference | MDN ReferencehasAttribute(name: str) -> bool
: Returns true if an element has a given attribute. W3Schools Reference | MDN ReferencehasAttributes() -> bool
: Returns true if an element has any attributes. W3Schools Reference | MDN ReferencegetAttributeNode(name: str)
: Returns an attribute node. W3Schools Reference | MDN ReferencesetAttributeNode(attr_node)
: Sets or changes an attribute node. W3Schools Reference | MDN ReferenceremoveAttributeNode(attr_node)
: Removes an attribute node, and returns the removed node. W3Schools Reference | MDN Reference
DOM Tree Manipulation
appendChild(child: Element)
: Appends a child element. Raises TypeError if child is not an Element. W3Schools Reference | MDN ReferenceremoveChild(child: Element)
: Removes a child element. Raises TypeError if child is not an Element. W3Schools Reference | MDN ReferencereplaceChild(new_child: Element, old_child: Element)
: Replaces a child element. Raises TypeError if arguments are not Elements. W3Schools Reference | MDN ReferenceinsertBefore(new_node: Element, reference_node: Element) -> Element
: Inserts a new child node before an existing child node. W3Schools Reference | MDN ReferencecloneNode(deep: bool = False) -> Element
: Clones an element. If deep is True, clones all descendants. W3Schools Reference | MDN Referenceremove()
: Removes an element from the DOM. W3Schools Reference | MDN Reference
Modern DOM Manipulation
append(*nodes)
: Adds (appends) one or several nodes (element) or strings after the last child of an element. W3Schools Reference | MDN Referenceafter(*nodes)
: Inserts one or more nodes (elements) or strings after an element. W3Schools Reference | MDN Referencebefore(*nodes)
: Inserts one or more nodes (elements) or strings before an element. W3Schools Reference | MDN ReferenceinsertAdjacentElement(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 ReferenceinsertAdjacentHTML(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 ReferenceinsertAdjacentText(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
querySelector(selector: str) -> Element
: Returns the first child element that matches a CSS selector(s). W3Schools Reference | MDN ReferencequerySelectorAll(selector: str) -> ElementList
: Returns all child elements that matches a CSS selector(s). W3Schools Reference | MDN ReferencegetElementsByClassName(class_name: str) -> ElementList
: Returns a collection of child elements with a given class name. W3Schools Reference | MDN ReferencegetElementsByTagName(tag_name: str) -> ElementList
: Returns a collection of child elements with a given tag name. W3Schools Reference | MDN Referenceclosest(selector: str) -> Element
: Searches the DOM tree for the closest element that matches a CSS selector. W3Schools Reference | MDN Referencematches(selector: str) -> bool
: Returns true if an element is matched by a given CSS selector. W3Schools Reference | MDN Reference
Element Information
getBoundingClientRect()
: Returns the size of an element and its position relative to the viewport. W3Schools Reference | MDN ReferencescrollIntoView(align_to_top: bool = True)
: Scrolls the element into the visible area of the browser window. W3Schools Reference | MDN Reference
Element Comparison and Testing
contains(other: Element) -> bool
: Returns true if a node is a descendant of a node. W3Schools Reference | MDN ReferencehasChildNodes() -> bool
: Returns true if an element has any child nodes. W3Schools Reference | MDN ReferencecompareDocumentPosition(other: Element) -> int
: Compares the document position of two elements. W3Schools Reference | MDN ReferenceisEqualNode(other: Element) -> bool
: Checks if two elements are equal. W3Schools Reference | MDN ReferenceisSameNode(other: Element) -> bool
: Checks if two elements are the same node. W3Schools Reference | MDN Reference
Utility Methods
normalize()
: Joins adjacent text nodes and removes empty text nodes in an element. W3Schools Reference | MDN ReferencetoString() -> str
: Converts an element to a string. W3Schools Reference | MDN ReferenceisDefaultNamespace(namespace_uri: str) -> bool
: Returns true if a given namespaceURI is the default. W3Schools Reference | MDN Reference
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
-
Cache element references: Store frequently accessed elements in variables rather than selecting them repeatedly.
-
Use specific selectors: When possible, use
getElementById()
as it's the fastest selection method. -
Check element existence: Always verify that elements exist before manipulating them.
-
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
- Use
-
Handle events efficiently: Remove event listeners when they're no longer needed to prevent memory leaks.
-
Use modern DOM methods: Prefer
append()
,before()
,after()
over older methods when possible. -
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