Spanish Total.js
English
Documentation For AI agents
Contents

HTML and XML parser

String.prototype.parseHTML(), HTMLElement and the methods of an element.

.md GitHub
On this page

API

method

String.prototype.parseHTML([trim])

Parses HTML into a tree of elements.
ParameterTypeDescription
trim? Boolean Trims text nodes. Default: false

Returns HTMLElement The root element.

Returns the root element; its children are the top-level nodes. Comments are removed. <script>, <style> and <template> keep their content as text. With trim: true the text nodes are trimmed.

String.prototype.parseXML2() parses XML the same way: every element keeps its prefix (soap:Body) and text of elements is joined with new lines by text().

Read links
var dom = html.parseHTML();
var links = dom.find('a').map(function(a) {
	return { url: a.attr('href'), text: a.text() };
});
XML
var xml = body.parseXML2();
var items = xml.find('*:item'); // any prefix
class

HTMLElement

An element (or a text node) of a tree from parseHTML().
PropertyDescription
tagNameTag name in upper case, TEXT for a text node
rawTag name as written
prefixXML prefix with the colon, such as SOAP:
attrsAttributes as an object
childrenChild nodes
parentNodeParent element
textContentText of a TEXT node
innerHTML, outerHTML, innerTextGetters for html(), the element with its tag, and text()
Walk
var dom = '<ul><li>A</li><li>B</li></ul>'.parseHTML();
var ul = dom.children[0];
ul.tagName;		   // 'UL'
ul.children.length;   // 2
ul.outerHTML;		 // '<ul><li>A</li><li>B</li></ul>'
method

element.find(selector)

Finds elements below this element.
ParameterTypeDescription
selector String CSS-like selector.

Returns Array Found elements.

Supports tag names, *, #id, .class, [attr="value"], [attr] (the element has the attribute), prefix: and *:name for XML, descendants (div p), children (div > p, or > p for direct children of this element) and several selectors separated by commas.

The result is an array with the methods aclass(), rclass(), tclass(), attr(), attrd(), find(), html() (same as toString()) and text(), applied to all found elements.

Find
dom.find('table.data > tr td').text();
dom.find('a').attr('rel', 'nofollow');
Elements with an attribute
var dom = html.parseHTML();
var images = dom.find('img[alt]');      // images with an alt text
var ids = dom.find('[data-id]');
method

element.parent()

Returns the parent element.

Returns HTMLElement The parent.

The same as element.parentNode.

Parent
var td = dom.find('td.price')[0];
var row = td.parent();
method

element.browse(fn, [reverse])

Calls a function for every node below this one.
ParameterTypeDescription
fn Function function(node); true skips the children.
reverse? Boolean Walks the parents. Default: false

Returns HTMLElement This element.

fn(node) is called for each node below, text nodes (tagName TEXT) included, depth first. Return true to skip the children of that element. With reverse: true it goes up through the parents instead.

Collect
var tags = {};
dom.browse(function(el) {
	tags[el.tagName] = (tags[el.tagName] || 0) + 1;
});
method

element.attr(name, [value])

Reads or sets an attribute.
ParameterTypeDescription
name String Attribute name.
value? Object New value.

Returns String The value when reading, otherwise the element.

Without value it returns the attribute. An empty value or null removes it; other values are stored as strings.

Attributes
var href = a.attr('href');
a.attr('rel', 'nofollow');
a.attr('target', null);
method

element.attrd(name, [value])

Reads or sets a data- attribute.
ParameterTypeDescription
name String Name without data-.
value? Object New value.

Returns String The value when reading, otherwise the element.

attrd('id') is attr('data-id').

Data
el.attrd('id', 123);
el.attrd('id'); // '123'
method

element.aclass(cls)

Adds classes.
ParameterTypeDescription
cls String Class names.

Returns HTMLElement This element.

Several classes are separated by spaces or commas.

Add
el.aclass('active selected');
method

element.rclass(cls)

Removes classes.
ParameterTypeDescription
cls String Class names.

Returns HTMLElement This element.

Several classes are separated by spaces or commas.

Remove
el.rclass('hidden');
method

element.tclass(cls, [value])

Toggles classes.
ParameterTypeDescription
cls String Class names.
value? Boolean Force add or remove.

Returns HTMLElement This element.

Without value each class is switched; true adds and false removes.

Toggle
el.tclass('active', item.id === current);
method

element.hclass(cls)

Tests a class.
ParameterTypeDescription
cls String One class name.

Returns Boolean

Returns true when the element has the class.

Test
if (el.hclass('price'))
	console.log(el.text());
method

element.css(key, [value])

Sets inline styles.
ParameterTypeDescription
key String|Object Property or object.
value? String Value; empty removes.

Returns HTMLElement This element.

Accepts a property and a value, or an object of properties. An empty value removes the property from the style attribute.

Styles
el.css('color', 'red');
el.css({ width: '100px', display: '' });
method

element.remove()

Removes the element from its parent.

Returns HTMLElement The removed element.

Remove scripts
dom.find('script').forEach(function(el) {
	el.remove();
});
method

element.append(html)

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

Returns HTMLElement The new element or elements.

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

Append
ul.append('<li>New</li>');
method

element.prepend(html)

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

Returns HTMLElement The parsed root.

Returns the parsed root of the new HTML.

Prepend
body.prepend('<p>Notice</p>');
method

element.text()

Returns the text of the element.

Returns String Text.

Text nodes are joined and decoded; text of block elements (div, p, headings, lists, tables...) is separated by new lines.

Text
'<p>Hello <b>world</b></p>'.parseHTML().text(); // 'Hello world'
method

element.html([formatted])

Returns the inner HTML.
ParameterTypeDescription
formatted? Boolean Indents the output. Default: false

Returns String HTML.

formatted: true puts each node on a new line with tabs. toString(formatted, outer) does the same and with outer: true includes the element itself.

Serialize
var html = dom.html();
var pretty = dom.html(true);
Made in Europe