-
Notifications
You must be signed in to change notification settings - Fork 2
Element
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.
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
-
id -> str
: Sets or returns the value of the id attribute of an element. W3Schools Reference | MDN Reference -
tagName -> str
: Returns the tag name of an element (e.g., "DIV", "P", "BUTTON"). W3Schools Reference | MDN Reference -
className -> str
: Sets or returns the value of the class attribute of an element. W3Schools Reference | MDN Reference -
classList
: Returns the class name(s) of an element as a DOMTokenList. W3Schools Reference | MDN Reference -
attributes
: Returns a NamedNodeMap of an element's attributes. W3Schools Reference | MDN Reference
-
innerText -> str
: Gets or sets the inner text of the element (text content only, no HTML). W3Schools Reference | MDN Reference -
innerHTML -> str
: Gets or sets the inner HTML of the element. Warning: This can lead to XSS vulnerabilities if not sanitized properly. W3Schools Reference | MDN Reference -
textContent -> str
: Sets or returns the textual content of a node and its descendants (similar to innerText but with some differences). W3Schools Reference | MDN Reference -
outerHTML -> str
: Sets or returns the content of an element (including the start tag and the end tag). W3Schools Reference | MDN Reference -
outerText -> str
: Sets or returns the outer text content of a node and its descendants. W3Schools Reference | MDN Reference -
value
: Gets or sets the value of a form element (input, textarea, select, etc.). W3Schools Reference | MDN Reference
-
accessKey -> str
: Sets or returns the accesskey attribute of an element. W3Schools Reference | MDN Reference -
contentEditable -> str
: Sets or returns whether the content of an element is editable or not. W3Schools Reference | MDN Reference -
isContentEditable -> bool
: Returns true if an element's content is editable. W3Schools Reference | MDN Reference -
tabIndex -> int
: Sets or returns the value of the tabindex attribute of an element. W3Schools Reference | MDN Reference -
title -> str
: Sets or returns the value of the title attribute of an element (tooltip text). W3Schools Reference | MDN Reference -
dir -> str
: Sets or returns the value of the dir attribute of an element (text direction). W3Schools Reference | MDN Reference -
lang -> str
: Sets or returns the value of the lang attribute of an element. W3Schools Reference | MDN Reference
-
clientHeight -> int
: Returns the height of an element, including padding but excluding border, scrollbar, and margin. W3Schools Reference | MDN Reference -
clientWidth -> int
: Returns the width of an element, including padding but excluding border, scrollbar, and margin. W3Schools Reference | MDN Reference -
clientLeft -> int
: Returns the width of the left border of an element. W3Schools Reference | MDN Reference -
clientTop -> int
: Returns the width of the top border of an element. W3Schools Reference | MDN Reference -
offsetHeight -> int
: Returns the height of an element, including padding, border and scrollbar. W3Schools Reference | MDN Reference -
offsetWidth -> int
: Returns the width of an element, including padding, border and scrollbar. W3Schools Reference | MDN Reference -
offsetLeft -> int
: Returns the horizontal offset position of an element relative to its offset parent. W3Schools Reference | MDN Reference -
offsetTop -> int
: Returns the vertical offset position of an element relative to its offset parent. W3Schools Reference | MDN Reference -
offsetParent
: Returns the offset container of an element. W3Schools Reference | MDN Reference
-
scrollHeight -> int
: Returns the entire height of an element, including padding. W3Schools Reference | MDN Reference -
scrollWidth -> int
: Returns the entire width of an element, including padding. W3Schools Reference | MDN Reference -
scrollLeft -> int
: Sets or returns the number of pixels an element's content is scrolled horizontally. W3Schools Reference | MDN Reference -
scrollTop -> int
: Sets or returns the number of pixels an element's content is scrolled vertically. W3Schools Reference | MDN Reference
-
parentNode
: Returns the parent node of an element. W3Schools Reference | MDN Reference -
parentElement
: Returns the parent element node of an element. W3Schools Reference | MDN Reference -
childNodes
: Returns a NodeList of an element's child nodes (includes text nodes). W3Schools Reference | MDN Reference -
children
: Returns an HTMLCollection of an element's child elements (elements only, no text nodes). W3Schools Reference | MDN Reference -
childElementCount -> int
: Returns an element's number of child elements. W3Schools Reference | MDN Reference -
firstChild
: Returns the first child node of an element. W3Schools Reference | MDN Reference -
firstElementChild
: Returns the first child element of an element. W3Schools Reference | MDN Reference -
lastChild
: Returns the last child node of an element. W3Schools Reference | MDN Reference -
lastElementChild
: Returns the last child element of an element. W3Schools Reference | MDN Reference -
nextSibling
: Returns the next node at the same node tree level. W3Schools Reference | MDN Reference -
nextElementSibling
: Returns the next element at the same node tree level. W3Schools Reference | MDN Reference -
previousSibling
: Returns the previous node at the same node tree level. W3Schools Reference | MDN Reference -
previousElementSibling
: Returns the previous element at the same node tree level. W3Schools Reference | MDN Reference
-
nodeName -> str
: Returns the name of a node (usually the tag name for elements). W3Schools Reference | MDN Reference -
nodeType -> int
: Returns the node type of a node (1 for elements). W3Schools Reference | MDN Reference -
nodeValue -> str
: Sets or returns the value of a node (null for elements). W3Schools Reference | MDN Reference -
ownerDocument
: Returns the root element (document object) for an element. W3Schools Reference | MDN Reference -
namespaceURI -> str
: Returns the namespace URI of an element. W3Schools Reference | MDN Reference
-
style -> Style
: Gets the style object of the element for CSS manipulation. W3Schools Reference | MDN Reference
-
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()
: Gives focus to an element. W3Schools Reference | MDN Reference -
blur()
: Removes focus from an element. W3Schools Reference | MDN Reference -
click()
: Simulates a mouse-click on an element. W3Schools Reference | MDN Reference
-
getAttribute(name: str) -> str
: Returns the value of an element's attribute. W3Schools Reference | MDN Reference -
setAttribute(attr_name: str, value: str)
: Sets an attribute on the element. W3Schools Reference | MDN Reference -
removeAttribute(name: str)
: Removes an attribute from an element. W3Schools Reference | MDN Reference -
hasAttribute(name: str) -> bool
: Returns true if an element has a given attribute. W3Schools Reference | MDN Reference -
hasAttributes() -> bool
: Returns true if an element has any attributes. W3Schools Reference | MDN Reference -
getAttributeNode(name: str)
: Returns an attribute node. W3Schools Reference | MDN Reference -
setAttributeNode(attr_node)
: Sets or changes an attribute node. W3Schools Reference | MDN Reference -
removeAttributeNode(attr_node)
: Removes an attribute node, and returns the removed node. W3Schools Reference | MDN Reference
-
appendChild(child: Element)
: Appends a child element. Raises TypeError if child is not an Element. W3Schools Reference | MDN Reference -
removeChild(child: Element)
: Removes a child element. Raises TypeError if child is not an Element. W3Schools Reference | MDN Reference -
replaceChild(new_child: Element, old_child: Element)
: Replaces a child element. Raises TypeError if arguments are not Elements. W3Schools Reference | MDN Reference -
insertBefore(new_node: Element, reference_node: Element) -> Element
: Inserts a new child node before an existing child node. W3Schools Reference | MDN Reference -
cloneNode(deep: bool = False) -> Element
: Clones an element. If deep is True, clones all descendants. W3Schools Reference | MDN Reference -
remove()
: Removes an element from the DOM. W3Schools Reference | MDN Reference
-
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
-
querySelector(selector: str) -> Element
: Returns the first child element that matches a CSS selector(s). W3Schools Reference | MDN Reference -
querySelectorAll(selector: str) -> ElementList
: Returns all child elements that matches a CSS selector(s). W3Schools Reference | MDN Reference -
getElementsByClassName(class_name: str) -> ElementList
: Returns a collection of child elements with a given class name. W3Schools Reference | MDN Reference -
getElementsByTagName(tag_name: str) -> ElementList
: Returns a collection of child elements with a given tag name. W3Schools Reference | MDN Reference -
closest(selector: str) -> Element
: Searches the DOM tree for the closest element that matches a CSS selector. W3Schools Reference | MDN Reference -
matches(selector: str) -> bool
: Returns true if an element is matched by a given CSS selector. W3Schools Reference | MDN Reference
-
getBoundingClientRect()
: Returns the size of an element and its position relative to the viewport. W3Schools Reference | MDN Reference -
scrollIntoView(align_to_top: bool = True)
: Scrolls the element into the visible area of the browser window. W3Schools Reference | MDN Reference
-
contains(other: Element) -> bool
: Returns true if a node is a descendant of a node. W3Schools Reference | MDN Reference -
hasChildNodes() -> bool
: Returns true if an element has any child nodes. W3Schools Reference | MDN Reference -
compareDocumentPosition(other: Element) -> int
: Compares the document position of two elements. W3Schools Reference | MDN Reference -
isEqualNode(other: Element) -> bool
: Checks if two elements are equal. W3Schools Reference | MDN Reference -
isSameNode(other: Element) -> bool
: Checks if two elements are the same node. W3Schools Reference | MDN Reference
-
normalize()
: Joins adjacent text nodes and removes empty text nodes in an element. W3Schools Reference | MDN Reference -
toString() -> str
: Converts an element to a string. W3Schools Reference | MDN Reference -
isDefaultNamespace(namespace_uri: str) -> bool
: Returns true if a given namespaceURI is the default. W3Schools Reference | MDN Reference
(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
(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)
(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
(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
(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
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)
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()
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")
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))
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)
-
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.
- 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