HTML parser
String.parseHTML(), HTMLElement and the methods of a node.
On this page
API
method
String.parseHTML([trim])
Parses an HTML string into a tree of HTMLElement nodes.
String.parseHTML([trim])| Parameter | Type | Description |
|---|---|---|
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.
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.
HTMLElementProperties: 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.
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.
node.find(selector)| Parameter | Type | Description |
|---|---|---|
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().
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.
node.closest(selector)| Parameter | Type | Description |
|---|---|---|
selector |
String |
The selector. |
Returns Array The matching ancestors.
Searches from the parent up to the root.
var form = input.closest('form')[0];
method
node.parent()
Returns the parent element.
node.parent()Returns HTMLElement
The same as node.parentNode.
var li = dom.find('a')[0].parent();
method
node.browse(fn, [reverse])
Walks through all descendant elements.
node.browse(fn, [reverse])| Parameter | Type | Description |
|---|---|---|
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.
var count = 0;
dom.browse(function(node) {
count++;
});
method
node.attr(name, [value])
Reads or sets an attribute.
node.attr(name, [value])| Parameter | Type | Description |
|---|---|---|
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.
dom.find('img')[0].attr('alt', 'Logo');
method
node.attrd(name, [value])
Reads or sets a data- attribute.
node.attrd(name, [value])| Parameter | Type | Description |
|---|---|---|
name |
String |
The name without data-. |
value? |
String |
The new value. |
Returns String|HTMLElement
The same as node.attr('data-' + name, value).
var id = node.attrd('id');
method
node.aclass(cls)
Adds CSS classes.
node.aclass(cls)| Parameter | Type | Description |
|---|---|---|
cls |
String |
The class names. |
Returns HTMLElement
More classes can be separated by a space or a comma.
node.aclass('active highlighted');
method
node.rclass(cls)
Removes CSS classes.
node.rclass(cls)| Parameter | Type | Description |
|---|---|---|
cls |
String |
The class names. |
Returns HTMLElement
More classes can be separated by a space or a comma.
node.rclass('hidden');
method
node.tclass(cls, [value])
Toggles CSS classes.
node.tclass(cls, [value])| Parameter | Type | Description |
|---|---|---|
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.
node.tclass('selected', item.id === current);
method
node.hclass(cls)
Checks a CSS class.
node.hclass(cls)| Parameter | Type | Description |
|---|---|---|
cls |
String |
One class name. |
Returns Boolean
Returns true when the element has the class.
if (node.hclass('external'))
node.attr('target', '_blank');
method
node.css(key, [value])
Sets inline styles.
node.css(key, [value])| Parameter | Type | Description |
|---|---|---|
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.
node.css('color', 'red');
node.css({ 'font-weight': 'bold', color: '' });
method
node.remove()
Removes the element from its parent.
node.remove()Returns HTMLElement The removed element.
for (var script of dom.find('script'))
script.remove();
method
node.append(html)
Parses HTML and adds it to the end of the children.
node.append(html)| Parameter | Type | Description |
|---|---|---|
html |
String |
The HTML to add. |
Returns HTMLElement|Array
Returns the new element, or an array when the HTML has more top-level nodes.
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.
node.prepend(html)| Parameter | Type | Description |
|---|---|---|
html |
String |
The HTML to add. |
Returns HTMLElement
Returns the root of the parsed HTML (not the new element).
dom.find('body')[0].prepend('<header>Top</header>');
method
node.text()
Returns the text of the element without tags.
node.text()Returns String
HTML entities are decoded (& becomes &). node.innerText returns the text without decoding.
'<p>A & B</p>'.parseHTML().find('p')[0].text();
// A & B
method
node.html([formatted])
Serializes the element back to HTML.
node.html([formatted])| Parameter | Type | Description |
|---|---|---|
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.
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.
elements.html([formatted])| Parameter | Type | Description |
|---|---|---|
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().
var items = dom.find('li');
items.aclass('item').attrd('ready', '1');
console.log(items.html());