Spanish Total.js
English
Documentation For AI agents
Contents

HTML parser

String.parseHTML(), HTMLElement and the methods of a node.

.md GitHub
On this page

API

method

String.parseHTML([trim])

Parses an HTML string into a tree of HTMLElement nodes.
ParameterTypeDescription
trim? Boolean Trims text nodes and skips empty ones. Default: false

Returns HTMLElement The root element.

Returns a root element without a tag name; its children are the top-level nodes. Comments, <!DOCTYPE> and <?xml ?> declarations are skipped. A missing end tag closes at the end of the input. Void tags (br, hr, img, input, meta, link, source, area, col, embed, track) have no children.

Find all links
var dom = html.parseHTML(true);
var links = dom.find('a');
for (var a of links)
	console.log(a.attr('href'), a.text());
class

HTMLElement

A node of a parsed HTML tree.

Properties: tagName (upper case, TEXT for text nodes), raw (the tag name as written), attrs (an object of attributes), children, parentNode, textContent (text nodes only), unpair (true for void tags), innerHTML and innerText (getters). A tag with a namespace (<g:item>) also has prefix (G:). All changing methods return the element, so you can chain them.

Read and change a node
var dom = '<div class="box"><p data-id="1">Hello</p></div>'.parseHTML();
var p = dom.find('p')[0];
console.log(p.tagName, p.attrs, p.parentNode.tagName);
// P { 'data-id': '1' } DIV
method

node.find(selector)

Finds the descendant elements that match a selector.
ParameterTypeDescription
selector String The selector.

Returns Array The matching elements.

Supported selectors: a tag name (div), *, #id, .class, an attribute value ([name="value"]), a descendant (div p) and a direct child (div > p). Separate more selectors with a comma. A namespace prefix ending with a colon (g:) matches all tags of that namespace. The result is an array with the extra methods of elements.html().

Selectors
var dom = html.parseHTML();
var images = dom.find('img[alt="Logo"]');
var items = dom.find('ul.menu > li');
var both = dom.find('h1, h2');
method

node.closest(selector)

Finds the ancestors that match a selector.
ParameterTypeDescription
selector String The selector.

Returns Array The matching ancestors.

Searches from the parent up to the root.

Find the parent form
var form = input.closest('form')[0];
method

node.parent()

Returns the parent element.

Returns HTMLElement

The same as node.parentNode.

Parent
var li = dom.find('a')[0].parent();
method

node.browse(fn, [reverse])

Walks through all descendant elements.
ParameterTypeDescription
fn Function(node) Called for each element.
reverse? Boolean Walks to the ancestors instead. Default: false

Returns HTMLElement The element itself.

The function is called for each element (text nodes are skipped). Return true to skip the children of that element. With reverse it walks up through the ancestors.

Count elements
var count = 0;
dom.browse(function(node) {
	count++;
});
method

node.attr(name, [value])

Reads or sets an attribute.
ParameterTypeDescription
name String The attribute name.
value? String The new value.

Returns String|HTMLElement The value when reading, otherwise the element.

Without value it returns the attribute. null or an empty string removes the attribute; any other value is stored as a string.

Set alt
dom.find('img')[0].attr('alt', 'Logo');
method

node.attrd(name, [value])

Reads or sets a data- attribute.
ParameterTypeDescription
name String The name without data-.
value? String The new value.

Returns String|HTMLElement

The same as node.attr('data-' + name, value).

Read data-id
var id = node.attrd('id');
method

node.aclass(cls)

Adds CSS classes.
ParameterTypeDescription
cls String The class names.

Returns HTMLElement

More classes can be separated by a space or a comma.

Add classes
node.aclass('active highlighted');
method

node.rclass(cls)

Removes CSS classes.
ParameterTypeDescription
cls String The class names.

Returns HTMLElement

More classes can be separated by a space or a comma.

Remove a class
node.rclass('hidden');
method

node.tclass(cls, [value])

Toggles CSS classes.
ParameterTypeDescription
cls String The class names.
value? Boolean Forces adding or removing.

Returns HTMLElement

Without value it adds missing classes and removes present ones. With value it adds the classes when value is truthy and removes them when it is falsy.

Toggle by condition
node.tclass('selected', item.id === current);
method

node.hclass(cls)

Checks a CSS class.
ParameterTypeDescription
cls String One class name.

Returns Boolean

Returns true when the element has the class.

Check
if (node.hclass('external'))
	node.attr('target', '_blank');
method

node.css(key, [value])

Sets inline styles.
ParameterTypeDescription
key String|Object The property, or an object { property: value }.
value? String The value.

Returns HTMLElement

Accepts a property and a value, or an object of properties. An empty value removes the property. The result is written to the style attribute.

Styles
node.css('color', 'red');
node.css({ 'font-weight': 'bold', color: '' });
method

node.remove()

Removes the element from its parent.

Returns HTMLElement The removed element.

Remove all scripts
for (var script of dom.find('script'))
	script.remove();
method

node.append(html)

Parses HTML and adds it to the end of the children.
ParameterTypeDescription
html String The HTML to add.

Returns HTMLElement|Array

Returns the new element, or an array when the HTML has more top-level nodes.

Append
var li = dom.find('ul')[0].append('<li>New</li>');
method

node.prepend(html)

Parses HTML and adds it to the beginning of the children.
ParameterTypeDescription
html String The HTML to add.

Returns HTMLElement

Returns the root of the parsed HTML (not the new element).

Prepend
dom.find('body')[0].prepend('<header>Top</header>');
method

node.text()

Returns the text of the element without tags.

Returns String

HTML entities are decoded (& becomes &). node.innerText returns the text without decoding.

Read text
'<p>A &amp; B</p>'.parseHTML().find('p')[0].text();
// A & B
method

node.html([formatted])

Serializes the element back to HTML.
ParameterTypeDescription
formatted? Boolean Indents the output. Default: false

Returns String

For the root it serializes the children. formatted puts each node on its own line with tab indentation. node.toString() is the same method. Empty class, id and data- attributes are left out.

Change and save
var dom = html.parseHTML();
dom.find('img').attr('loading', 'lazy');
var output = dom.html();
method

elements.html([formatted])

since 0.0.98 Serializes all found elements to one HTML string.
ParameterTypeDescription
formatted? Boolean Puts each element on its own line. Default: false

Returns String

The array returned by find() and closest() also has aclass(), rclass(), tclass(), attr() and attrd(), which apply to each element and return the array. toString() is an alias of html().

Work with all results
var items = dom.find('li');
items.aclass('item').attrd('ready', '1');
console.log(items.html());
Made in Europe