Spanish Total.js
English
Documentation For AI agents
Contents

HTML parser

Parse HTML on the server into a tree of nodes that you can search and change.

.md GitHub

String.parseHTML([trim]) turns HTML into a tree of nodes. It is a small parser for reading and editing documents on the server, not a full browser DOM.

var dom = '<ul class="menu"><li><a href="/docs/">Home</a></li><li><a href="https://www.totaljs.com">Total.js</a></li></ul>'.parseHTML(true);

var links = dom.find('a');
for (var a of links) {
    if (a.attr('href').indexOf('http') === 0)
        a.attr('target', '_blank').aclass('external');
}

console.log(dom.html());

find() supports tag names, *, #id, .class, [attr="value"], descendants (ul li), direct children (ul > li) and more selectors separated by commas. closest() searches the ancestors. The result is an array with a few extra methods (aclass(), rclass(), tclass(), attr(), attrd() and html()) that apply to all found elements.

A node has tagName (upper case), attrs, children, parentNode and, for text nodes, textContent. You can change it with attr(), attrd(), aclass(), rclass(), tclass(), css(), append(), prepend() and remove(), and serialize it with html([formatted]). text() returns the text without tags and with decoded entities:

var dom = '<article><h1>News & updates</h1><p>Text</p><script>track();</script></article>'.parseHTML();

for (var script of dom.find('script'))
    script.remove();

var title = dom.find('h1')[0].text(); // News & updates
var clean = dom.html(true);

Comments are removed and <!DOCTYPE> is skipped.

Made in Europe