HTML and XML parser
String.prototype.parseHTML(), HTMLElement and the methods of an element.
On this page
API
method
String.prototype.parseHTML([trim])
Parses HTML into a tree of elements.
String.prototype.parseHTML([trim])| Parameter | Type | Description |
|---|---|---|
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().
var dom = html.parseHTML();
var links = dom.find('a').map(function(a) {
return { url: a.attr('href'), text: a.text() };
});
var xml = body.parseXML2();
var items = xml.find('*:item'); // any prefix
class
HTMLElement
An element (or a text node) of a tree from parseHTML().
HTMLElement| Property | Description |
|---|---|
tagName | Tag name in upper case, TEXT for a text node |
raw | Tag name as written |
prefix | XML prefix with the colon, such as SOAP: |
attrs | Attributes as an object |
children | Child nodes |
parentNode | Parent element |
textContent | Text of a TEXT node |
innerHTML, outerHTML, innerText | Getters for html(), the element with its tag, and text() |
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.
element.find(selector)| Parameter | Type | Description |
|---|---|---|
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.
dom.find('table.data > tr td').text();
dom.find('a').attr('rel', 'nofollow');
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.
element.parent()Returns HTMLElement The parent.
The same as element.parentNode.
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.
element.browse(fn, [reverse])| Parameter | Type | Description |
|---|---|---|
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.
var tags = {};
dom.browse(function(el) {
tags[el.tagName] = (tags[el.tagName] || 0) + 1;
});
method
element.attr(name, [value])
Reads or sets an attribute.
element.attr(name, [value])| Parameter | Type | Description |
|---|---|---|
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.
var href = a.attr('href');
a.attr('rel', 'nofollow');
a.attr('target', null);
method
element.attrd(name, [value])
Reads or sets a data- attribute.
element.attrd(name, [value])| Parameter | Type | Description |
|---|---|---|
name |
String |
Name without data-. |
value? |
Object |
New value. |
Returns String The value when reading, otherwise the element.
attrd('id') is attr('data-id').
el.attrd('id', 123);
el.attrd('id'); // '123'
method
element.aclass(cls)
Adds classes.
element.aclass(cls)| Parameter | Type | Description |
|---|---|---|
cls |
String |
Class names. |
Returns HTMLElement This element.
Several classes are separated by spaces or commas.
el.aclass('active selected');
method
element.rclass(cls)
Removes classes.
element.rclass(cls)| Parameter | Type | Description |
|---|---|---|
cls |
String |
Class names. |
Returns HTMLElement This element.
Several classes are separated by spaces or commas.
el.rclass('hidden');
method
element.tclass(cls, [value])
Toggles classes.
element.tclass(cls, [value])| Parameter | Type | Description |
|---|---|---|
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.
el.tclass('active', item.id === current);
method
element.hclass(cls)
Tests a class.
element.hclass(cls)| Parameter | Type | Description |
|---|---|---|
cls |
String |
One class name. |
Returns Boolean
Returns true when the element has the class.
if (el.hclass('price'))
console.log(el.text());
method
element.css(key, [value])
Sets inline styles.
element.css(key, [value])| Parameter | Type | Description |
|---|---|---|
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.
el.css('color', 'red');
el.css({ width: '100px', display: '' });
method
element.remove()
Removes the element from its parent.
element.remove()Returns HTMLElement The removed element.
dom.find('script').forEach(function(el) {
el.remove();
});
method
element.append(html)
Parses HTML and adds it at the end of the children.
element.append(html)| Parameter | Type | Description |
|---|---|---|
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.
ul.append('<li>New</li>');
method
element.prepend(html)
Parses HTML and adds it at the beginning of the children.
element.prepend(html)| Parameter | Type | Description |
|---|---|---|
html |
String |
HTML to add. |
Returns HTMLElement The parsed root.
Returns the parsed root of the new HTML.
body.prepend('<p>Notice</p>');
method
element.text()
Returns the text of the element.
element.text()Returns String Text.
Text nodes are joined and decoded; text of block elements (div, p, headings, lists, tables...) is separated by new lines.
'<p>Hello <b>world</b></p>'.parseHTML().text(); // 'Hello world'
method
element.html([formatted])
Returns the inner HTML.
element.html([formatted])| Parameter | Type | Description |
|---|---|---|
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.
var html = dom.html();
var pretty = dom.html(true);