hast utility that turns HTML into a syntax tree.
- What is this?
- When should I use this?
- Install
- Use
- API
- Examples
- Syntax
- Types
- Compatibility
- Security
- Related
- Contribute
- License
This package is a utility that takes HTML input and turns it into a hast syntax tree.
If you want to handle syntax trees manually, use this.
Use parse5 instead when you just want to parse HTML and donβt care
about hast.
You can also use hast-util-from-parse5 and
parse5 yourself, or use the rehype plugin
rehype-parse, which wraps this utility to also parse HTML at
a higher-level (easier) abstraction.
xast-util-from-xml can be used if you are dealing with
XML instead of HTML.
If you might run in a browser and prefer a ligher alternative, while not caring
about positional info, parse errors, and consistency across browsers, use
hast-util-from-html-isomorphic, which
wraps this in Node and uses browser APIs otherwise.
Finally you can use the utility hast-util-to-html for
the inverse of this utility.
It turns hast into HTML.
This package is ESM only. In Node.js (version 16+), install with npm:
npm install hast-util-from-htmlIn Deno with esm.sh:
import {fromHtml} from 'https://esm.sh/hast-util-from-html@2'In browsers with esm.sh:
<script type="module">
import {fromHtml} from 'https://esm.sh/hast-util-from-html@2?bundle'
</script>import {fromHtml} from 'hast-util-from-html'
const tree = fromHtml('<h1>Hello, world!</h1>', {fragment: true})
console.log(tree)Yields:
{
type: 'root',
children: [
{
type: 'element',
tagName: 'h1',
properties: {},
children: [Array],
position: [Object]
}
],
data: { quirksMode: false },
position: {
start: { line: 1, column: 1, offset: 0 },
end: { line: 1, column: 23, offset: 22 }
}
}This package exports the identifier fromHtml.
There is no default export.
Turn serialized HTML into a hast tree.
value(Compatible) β serialized HTML to parseoptions(Options, optional) β configuration
Tree (Root).
Known names of parse errors (TypeScript type).
type ErrorCode =
| 'abandonedHeadElementChild'
| 'abruptClosingOfEmptyComment'
| 'abruptDoctypePublicIdentifier'
// β¦ see readme on `options[key in ErrorCode]` above.Error severity (TypeScript type).
export type ErrorSeverity =
// Turn the parse error off:
| 0
| false
// Turn the parse error into a warning:
| 1
| true
// Turn the parse error into an actual error: processing stops.
| 2Function called when encountering HTML parse errors.
error(VFileMessage) β message
Nothing (void).
Configuration (TypeScript type).
Which space the document is in ('html' or 'svg', default: 'html').
When an <svg> element is found in the HTML space, hast-util-from-html
already automatically switches to and from the SVG space when entering and
exiting it.
π Note: this is not an XML parser. It supports SVG as embedded in HTML. It does not support the features available in XML. Passing SVG files might break but fragments of modern SVG should be fine. Use
xast-util-from-xmlto parse XML.
π Note: make sure to set
fragment: trueifspace: 'svg'.
Add extra positional info about attributes, start tags, and end tags
(boolean, default: false).
Whether to parse as a fragment (boolean, default: false).
The default is to expect a whole document.
In document mode, unopened html, head, and body elements are opened.
Function called when encountering HTML parse errors
(OnError, optional).
Specific parse errors can be configured by setting their identifiers (see
ErrorCode) as keys directly in options to an
ErrorSeverity as value.
The list of parse errors:
abandonedHeadElementChildβ unexpected metadata element after head (example)abruptClosingOfEmptyCommentβ unexpected abruptly closed empty comment (example)abruptDoctypePublicIdentifierβ unexpected abruptly closed public identifier (example)abruptDoctypeSystemIdentifierβ unexpected abruptly closed system identifier (example)absenceOfDigitsInNumericCharacterReferenceβ unexpected non-digit at start of numeric character reference (example)cdataInHtmlContentβ unexpected CDATA section in HTML (example)characterReferenceOutsideUnicodeRangeβ unexpected too big numeric character reference (example)closingOfElementWithOpenChildElementsβ unexpected closing tag with open child elements (example)controlCharacterInInputStreamβ unexpected control character (example)controlCharacterReferenceβ unexpected control character reference (example)disallowedContentInNoscriptInHeadβ disallowed content inside<noscript>in<head>(example)duplicateAttributeβ unexpected duplicate attribute (example)endTagWithAttributesβ unexpected attribute on closing tag (example)endTagWithTrailingSolidusβ unexpected slash at end of closing tag (example)endTagWithoutMatchingOpenElementβ unexpected unopened end tag (example)eofBeforeTagNameβ unexpected end of file (example)eofInCdataβ unexpected end of file in CDATA (example)eofInCommentβ unexpected end of file in comment (example)eofInDoctypeβ unexpected end of file in doctype (example)eofInElementThatCanContainOnlyTextβ unexpected end of file in element that can only contain text (example)eofInScriptHtmlCommentLikeTextβ unexpected end of file in comment inside script (example)eofInTagβ unexpected end of file in tag (example)incorrectlyClosedCommentβ incorrectly closed comment (example)incorrectlyOpenedCommentβ incorrectly opened comment (example)invalidCharacterSequenceAfterDoctypeNameβ invalid sequence after doctype name (example)invalidFirstCharacterOfTagNameβ invalid first character in tag name (example)misplacedDoctypeβ misplaced doctype (example)misplacedStartTagForHeadElementβ misplaced<head>start tag (example)missingAttributeValueβ missing attribute value (example)missingDoctypeβ missing doctype before other content (example)missingDoctypeNameβ missing doctype name (example)missingDoctypePublicIdentifierβ missing public identifier in doctype (example)missingDoctypeSystemIdentifierβ missing system identifier in doctype (example)missingEndTagNameβ missing name in end tag (example)missingQuoteBeforeDoctypePublicIdentifierβ missing quote before public identifier in doctype (example)missingQuoteBeforeDoctypeSystemIdentifierβ missing quote before system identifier in doctype (example)missingSemicolonAfterCharacterReferenceβ missing semicolon after character reference (example)missingWhitespaceAfterDoctypePublicKeywordβ missing whitespace after public identifier in doctype (example)missingWhitespaceAfterDoctypeSystemKeywordβ missing whitespace after system identifier in doctype (example)missingWhitespaceBeforeDoctypeNameβ missing whitespace before doctype name (example)missingWhitespaceBetweenAttributesβ missing whitespace between attributes (example)missingWhitespaceBetweenDoctypePublicAndSystemIdentifiersβ missing whitespace between public and system identifiers in doctype (example)nestedCommentβ unexpected nested comment (example)nestedNoscriptInHeadβ unexpected nested<noscript>in<head>(example)nonConformingDoctypeβ unexpected non-conforming doctype declaration (example)nonVoidHtmlElementStartTagWithTrailingSolidusβ unexpected trailing slash on start tag of non-void element (example)noncharacterCharacterReferenceβ unexpected noncharacter code point referenced by character reference (example)noncharacterInInputStreamβ unexpected noncharacter character (example)nullCharacterReferenceβ unexpected NULL character referenced by character reference (example)openElementsLeftAfterEofβ unexpected end of file (example)surrogateCharacterReferenceβ unexpected surrogate character referenced by character reference (example)surrogateInInputStreamβ unexpected surrogate characterunexpectedCharacterAfterDoctypeSystemIdentifierβ invalid character after system identifier in doctype (example)unexpectedCharacterInAttributeNameβ unexpected character in attribute name (example)unexpectedCharacterInUnquotedAttributeValueβ unexpected character in unquoted attribute value (example)unexpectedEqualsSignBeforeAttributeNameβ unexpected equals sign before attribute name (example)unexpectedNullCharacterβ unexpected NULL character (example)unexpectedQuestionMarkInsteadOfTagNameβ unexpected question mark instead of tag name (example)unexpectedSolidusInTagβ unexpected slash in tag (example)unknownNamedCharacterReferenceβ unexpected unknown named character reference (example)
The following example shows the difference between parsing as a document and parsing as a fragment:
import {fromHtml} from 'hast-util-from-html'
const doc = '<title>Hi!</title><h1>Hello!</h1>'
console.log(fromHtml(doc))
console.log(fromHtml(doc, {fragment: true}))β¦yields (positional info and data omitted for brevity):
{
type: 'root',
children: [
{type: 'element', tagName: 'html', properties: {}, children: [Array]}
]
}{
type: 'root',
children: [
{type: 'element', tagName: 'title', properties: {}, children: [Array]},
{type: 'element', tagName: 'h1', properties: {}, children: [Array]}
]
}π Note: observe that when a whole document is expected (first example), missing elements are opened and closed.
The following example shows how whitespace is handled when around and directly
inside the <html> element:
import {fromHtml} from 'hast-util-from-html'
import {inspect} from 'unist-util-inspect'
const doc = `<!doctype html>
<html lang=en>
<head>
<title>Hi!</title>
</head>
<body>
<h1>Hello!</h1>
</body>
</html>`
console.log(inspect(fromHtml(doc)))β¦yields:
root[2] (1:1-9:8, 0-119)
β data: {"quirksMode":false}
ββ0 doctype (1:1-1:16, 0-15)
ββ1 element<html>[3] (2:1-9:8, 16-119)
β properties: {"lang":"en"}
ββ0 element<head>[3] (3:3-5:10, 33-72)
β β properties: {}
β ββ0 text "\n " (3:9-4:5, 39-44)
β ββ1 element<title>[1] (4:5-4:23, 44-62)
β β β properties: {}
β β ββ0 text "Hi!" (4:12-4:15, 51-54)
β ββ2 text "\n " (4:23-5:3, 62-65)
ββ1 text "\n " (5:10-6:3, 72-75)
ββ2 element<body>[3] (6:3-8:10, 75-111)
β properties: {}
ββ0 text "\n " (6:9-7:5, 81-86)
ββ1 element<h1>[1] (7:5-7:20, 86-101)
β β properties: {}
β ββ0 text "Hello!" (7:9-7:15, 90-96)
ββ2 text "\n \n" (7:20-9:1, 101-112)π Note: observe that the line ending before
<html>is ignored, the line ending and two spaces before<head>is moved inside it, and the line ending after</body>is moved before it.
This behavior is described by the HTML standard (see the section 13.2.6.4.1 βThe βinitialβ insertion modeβ and adjacent states) which we follow.
The changes to this meaningless whitespace should not matter, except when
formatting markup, in which case rehype-format can be used to
improve the source code.
The following example shows how HTML parse errors can be enabled and configured:
import {fromHtml} from 'hast-util-from-html'
const doc = `<!doctypehtml>
<title class="a" class="b">Helloβ¦</title>
<h1/>World!</h1>`
fromHtml(doc, {
onerror: console.log,
missingWhitespaceBeforeDoctypeName: 2, // Mark one as a fatal error.
nonVoidHtmlElementStartTagWithTrailingSolidus: false // Ignore one.
})β¦yields:
[1:10-1:10: Missing whitespace before doctype name] {
ancestors: undefined,
cause: undefined,
column: 10,
fatal: true,
line: 1,
place: {
start: { line: 1, column: 10, offset: 9 },
end: { line: 1, column: 10, offset: 9 }
},
reason: 'Missing whitespace before doctype name',
ruleId: 'missing-whitespace-before-doctype-name',
source: 'hast-util-from-html',
note: 'Unexpected `h`. Expected ASCII whitespace instead',
url: 'https://html.spec.whatwg.org/multipage/parsing.html#parse-error-missing-whitespace-before-doctype-name'
}
[2:23-2:23: Unexpected duplicate attribute] {
ancestors: undefined,
cause: undefined,
column: 23,
fatal: false,
line: 2,
place: {
start: { line: 2, column: 23, offset: 37 },
end: { line: 2, column: 23, offset: 37 }
},
reason: 'Unexpected duplicate attribute',
ruleId: 'duplicate-attribute',
source: 'hast-util-from-html',
note: 'Unexpectedly double attribute. Expected attributes to occur only once',
url: 'https://html.spec.whatwg.org/multipage/parsing.html#parse-error-duplicate-attribute'
}π§βπ« Info: messages in unified are warnings instead of errors. Other linters (such as ESLint) almost always use errors. Why? Those tools only check code style. They donβt generate, transform, and format code, which is what we focus on, too. Errors in unified mean the same as an exception in your JavaScript code: a crash. Thatβs why we use warnings instead, because we can continue doing work.
HTML is parsed according to WHATWG HTML (the living standard), which is also followed by browsers such as Chrome and Firefox.
This package is fully typed with TypeScript.
It exports the additional types
ErrorCode, ErrorSeverity,
OnError, and Options.
Projects maintained by the unified collective are compatible with maintained versions of Node.js.
When we cut a new major release, we drop support for unmaintained versions of
Node.
This means we try to keep the current release line, hast-util-from-html@^2,
compatible with Node.js 16.
Parsing HTML is safe but using user-provided content can open you up to a
cross-site scripting (XSS) attack.
Use hast-util-santize to make the hast tree safe.
hast-util-to-htmlβ serialize hasthast-util-sanitizeβ sanitize hastxast-util-from-xmlβ parse XML
See contributing.md in syntax-tree/.github for
ways to get started.
See support.md for ways to get help.
This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.
MIT Β© Titus Wormer