HTMLNode
A HTML node object, representing an element, or the document itself with name #document.
Unlike XMLNode , children are kept as an ordered list of strings and nodes, like in the browser DOM.
Usage:
lua Copy
local document = HTMLNode.fromString ( [[<ul id="list"><li>One<li class="active">Two</ul>]] )
print ( document:querySelector ( "#list > li.active" ):getText () ) -- Two
Constructor HTMLNode (name : string , attributes : ( table <string , string > | nil ), parent : ( HTMLNode | nil )): HTMLNode Fields Name Type Description namestring The tag name of the node, lowercase for HTML elements and #document for documents. attributesnil | table <string , string >The attributes of the node, boolean attributes have an empty value. parentHTMLNode | nil The parent node. childrennil | HTMLNode.Value[] The child nodes and text chunks in document order. doctypenil | string The DOCTYPE of a document, e.g. html.
Static functions createDocumentCreates an empty HTML5 document with html, head (with UTF-8 charset and optional title) and body elements. fromStringParses a HTML string into a document node.
function HTMLNode.createDocument (title? : string ): HTMLNode
Creates an empty HTML5 document with html, head (with UTF-8 charset and optional title) and body elements.
Parameters
Name Type Description titleoptional string The title of the document.
Returns
Type Name Description HTMLNode documentThe document node.
function HTMLNode.fromString (html_str : string , keep_whitespace? : boolean ): HTMLNode
Parses a HTML string into a document node.
The parser is lenient like a browser: it never fails, tag and attribute names are case-insensitive, attribute values may be unquoted or missing, void elements (br, img, ...) have no end tag, optional end tags (p, li, td, ...) are closed implicitly, stray end tags are ignored and script/style content is kept as raw text. Missing html, head and body elements are not created.
Inside svg and math names keep their case and /> closes the element.
By default whitespace is collapsed like a browser renders it and indentation is removed, pre, textarea, script and style keep it as is.
Comments and processing instructions are skipped, HTML 4 named and numeric character references are decoded.
Parameters
Name Type Description html_strstring The HTML string to parse. keep_whitespaceoptional boolean Whether to keep all whitespace in text, defaults to false.
Returns
Type Name Description HTMLNode documentThe document node, with the elements as children.
Methods addCreates a new element and appends it to the children of the node. addClassAdds the class to the class attribute of the node. appendAppends nodes or text to the end of the children, nodes are detached from their old parent first. clearRemoves all children of the node. closestReturns the closest element matching the CSS selector, starting with the node itself and going up through its ancestors. detachDetaches the node from its parent. getAttributeReturns the value of the attribute with the given name or nil if not found. getChildReturns the child (node or text chunk) at the given index, negative indices count from the end. getChildCountReturns the number of children (nodes and text chunks) of the node. getElementByIdReturns the first descendant element with the given id, or nil if not found. getElementsReturns the child elements of the node, skipping text. getElementsByClassNameReturns all descendant elements that have all of the given whitespace-separated classes. getElementsByTagNameReturns all descendant elements with the given tag name, * matches all elements. getFirstElementReturns the first child element of the node, skipping text. getInnerHTMLReturns the HTML string representation of the children of this node, like innerHTML in the browser DOM. getTextReturns the text content of the node and all its descendants, like textContent in the browser DOM. hasAttributeChecks whether the node has the attribute with the given name. hasClassChecks whether the node has the given class in its class attribute. insertInserts a node or text at the given index, nodes are detached from their old parent first. isDocumentChecks whether the node is a document. isEmptyChecks whether the node has no children. isVoidChecks whether the node is a void element, which has no end tag and no children, like br or img. iteratorReturns an iterator over the children of the node in document order, values are strings or nodes. matchesChecks whether the node matches the CSS selector, see :querySelector() for the supported syntax. querySelectorReturns the first descendant element matching the CSS selector, or nil if not found. querySelectorAllReturns all descendant elements matching the CSS selector in document order, see :querySelector() for the supported syn… removeRemoves the child at the given index or the given child node. removeAttributeRemoves the attribute with the given name. removeClassRemoves the class from the class attribute of the node, the attribute is removed when no classes are left. setAttributeSets the value of the attribute with the given name, true sets a boolean attribute, nil or false removes it. setTextReplaces all children of the node with the given text. toStringReturns the HTML string representation of this node, like outerHTML in the browser DOM, documents include their DOCTYPE.
function HTMLNode:add (name : string , attributes? : table <string , string >): HTMLNode
Creates a new element and appends it to the children of the node.
Parameters
Name Type Description namestring The tag name of the new element. attributesoptional table <string , string >The attributes of the new element.
Returns
Type Name Description HTMLNode childThe new element.
function HTMLNode:addClass (name : string ): HTMLNode
Adds the class to the class attribute of the node.
Parameters
Name Type Description namestring The class name.
Returns
Type Name Description HTMLNode selfThe node itself, for chaining.
function HTMLNode:append (... : HTMLNode.Value | any ): HTMLNode
Appends nodes or text to the end of the children, nodes are detached from their old parent first.
Usage:
lua Copy
local paragraph = HTMLNode ( "p" ):append ( "Hello " , HTMLNode ( "b" ):append ( "world" ), "!" )
print ( paragraph ) -- <p>Hello <b>world</b>!</p>
Parameters
Name Type Description ...HTMLNode.Value | any The nodes or text to append, other values are converted to strings.
Returns
Type Name Description HTMLNode selfThe node itself, for chaining.
function HTMLNode:clear (): HTMLNode
Removes all children of the node.
Returns
Type Name Description HTMLNode selfThe node itself, for chaining.
function HTMLNode:closest (selector : string ): HTMLNode | nil
Returns the closest element matching the CSS selector, starting with the node itself and going up through its ancestors.
Parameters
Name Type Description selectorstring The CSS selector.
Returns
Type Name Description HTMLNode | nil element
function HTMLNode:detach (): HTMLNode
Detaches the node from its parent.
Returns
Type Name Description HTMLNode selfThe node itself, for chaining.
function HTMLNode:getAttribute (name : string ): nil | string
Returns the value of the attribute with the given name or nil if not found.
Parameters
Name Type Description namestring The name of the attribute to get.
Returns
Type Name Description nil | string valueThe value of the attribute or nil if not found.
function HTMLNode:getChild (index : integer ): nil | HTMLNode.Value
Returns the child (node or text chunk) at the given index, negative indices count from the end.
Parameters
Name Type Description indexinteger The index of the child.
Returns
function HTMLNode:getChildCount (): integer
Returns the number of children (nodes and text chunks) of the node.
Returns
Type Name Description integer count
function HTMLNode:getElementById (id : string ): HTMLNode | nil
Returns the first descendant element with the given id, or nil if not found.
Parameters
Name Type Description idstring The id of the element.
Returns
Type Name Description HTMLNode | nil element
function HTMLNode:getElements (): HTMLNode[] , integer
Returns the child elements of the node, skipping text.
Returns
# HTMLNode:getElementsByClassName
function HTMLNode:getElementsByClassName (names : string ): HTMLNode[] , integer
Returns all descendant elements that have all of the given whitespace-separated classes.
Parameters
Name Type Description namesstring The class names, separated by whitespace.
Returns
# HTMLNode:getElementsByTagName
function HTMLNode:getElementsByTagName (name : string ): HTMLNode[] , integer
Returns all descendant elements with the given tag name, * matches all elements.
Parameters
Name Type Description namestring The tag name, case-insensitive.
Returns
# HTMLNode:getFirstElement
function HTMLNode:getFirstElement (): HTMLNode | nil
Returns the first child element of the node, skipping text.
Returns
Type Name Description HTMLNode | nil element
function HTMLNode:getInnerHTML (): string
Returns the HTML string representation of the children of this node, like innerHTML in the browser DOM.
Returns
Type Name Description string strThe HTML string representation of the children.
function HTMLNode:getText (): string
Returns the text content of the node and all its descendants, like textContent in the browser DOM.
Returns
Type Name Description string text
function HTMLNode:hasAttribute (name : string ): boolean
Checks whether the node has the attribute with the given name.
Parameters
Name Type Description namestring The name of the attribute.
Returns
Type Name Description boolean has_attribute
function HTMLNode:hasClass (name : string ): boolean
Checks whether the node has the given class in its class attribute.
Parameters
Name Type Description namestring The class name.
Returns
Type Name Description boolean has_class
function HTMLNode:insert (index : integer , value : HTMLNode.Value | any ): HTMLNode
Inserts a node or text at the given index, nodes are detached from their old parent first.
Parameters
Name Type Description indexinteger The index to insert at, clamped to the children range, negative indices count from the end. valueHTMLNode.Value | any The node or text to insert, other values are converted to strings.
Returns
Type Name Description HTMLNode selfThe node itself, for chaining.
function HTMLNode:isDocument (): boolean
Checks whether the node is a document.
Returns
Type Name Description boolean is_document
function HTMLNode:isEmpty (): boolean
Checks whether the node has no children.
Returns
Type Name Description boolean is_empty
function HTMLNode:isVoid (): boolean
Checks whether the node is a void element, which has no end tag and no children, like br or img.
Returns
Type Name Description boolean is_void
function HTMLNode:iterator (): fun (): ( ( integer | nil ), HTMLNode.Value )
Returns an iterator over the children of the node in document order, values are strings or nodes.
Returns
Type Name Description fun (): ( ( integer | nil ), HTMLNode.Value )fnThe iterator function.
function HTMLNode:matches (selector : string ): boolean
Checks whether the node matches the CSS selector, see :querySelector() for the supported syntax.
Parameters
Name Type Description selectorstring The CSS selector.
Returns
Type Name Description boolean is_matching
function HTMLNode:querySelector (selector : string ): HTMLNode | nil
Returns the first descendant element matching the CSS selector, or nil if not found.
Supported: type, *, #id, .class, attributes [a], [a=v], [a~=v], [a|=v], [a^=v], [a$=v], [a*=v] with optional i flag, combinators , >, +, ~, selector lists ,, pseudo-classes :first-child, :last-child, :only-child, :nth-child(), :nth-last-child(), the -of-type variants, :empty, :root and :not().
Parameters
Name Type Description selectorstring The CSS selector.
Returns
Type Name Description HTMLNode | nil element
# HTMLNode:querySelectorAll
function HTMLNode:querySelectorAll (selector : string ): HTMLNode[] , integer
Returns all descendant elements matching the CSS selector in document order, see :querySelector() for the supported syntax.
Parameters
Name Type Description selectorstring The CSS selector.
Returns
function HTMLNode:remove (child : integer | HTMLNode ): nil | HTMLNode.Value
Removes the child at the given index or the given child node.
Parameters
Name Type Description childinteger | HTMLNode The index of the child or the child node.
Returns
Type Name Description nil | HTMLNode.Value removedThe removed child, or nil if not found.
# HTMLNode:removeAttribute
function HTMLNode:removeAttribute (name : string ): HTMLNode
Removes the attribute with the given name.
Parameters
Name Type Description namestring The name of the attribute to remove.
Returns
Type Name Description HTMLNode selfThe node itself, for chaining.
function HTMLNode:removeClass (name : string ): HTMLNode
Removes the class from the class attribute of the node, the attribute is removed when no classes are left.
Parameters
Name Type Description namestring The class name.
Returns
Type Name Description HTMLNode selfThe node itself, for chaining.
function HTMLNode:setAttribute (name : string , value : any ): HTMLNode
Sets the value of the attribute with the given name, true sets a boolean attribute, nil or false removes it.
Parameters
Name Type Description namestring The name of the attribute to set. valueany The value of the attribute.
Returns
Type Name Description HTMLNode selfThe node itself, for chaining.
function HTMLNode:setText (text : string | any ): HTMLNode
Replaces all children of the node with the given text.
Parameters
Name Type Description textstring | any The text, other values are converted to strings.
Returns
Type Name Description HTMLNode selfThe node itself, for chaining.
function HTMLNode:toString (pretty? : boolean , level? : integer ): string
Returns the HTML string representation of this node, like outerHTML in the browser DOM, documents include their DOCTYPE.
Pretty formatting puts block elements on separate lines and trims the text next to them, so use compact output for exact data.
Parameters
Name Type Description prettyoptional boolean Whether to use pretty formatting (indentation and newlines). leveloptional integer The indentation level.
Returns
Type Name Description string strThe HTML string representation of this node.