hast-util-from-dom

Build Coverage Downloads Size Sponsors Backers Chat

hast utility to transform from a DOM tree.

Install

This package is ESM only: Node 12+ is needed to use it and it must be imported instead of required.

npm:

npm install hast-util-from-dom

Use

This utility is similar to hast-util-from-parse5, but is intended for browser use and therefore relies on the native DOM API instead of an external parsing library.

Say we have the following file, example.html:

<!doctype html><title>Hello!</title><h1 id="world">World!<!--after--><script src="example.js" charset="UTF-8"></script>

Suppose example.js is a bundled version of something like this:

import {inspect} from 'unist-util-inspect'
import {fromDom} from 'hast-util-from-dom'

const hast = fromDom(document)

console.log(inspect.noColor(hast))

Viewing example.html in a browser should yield the following in the console:

root[2]
β”œβ”€ doctype [name="html"]
└─ element[2] [tagName="html"]
   β”œβ”€ element[1] [tagName="head"]
   β”‚  └─ element[1] [tagName="title"]
   β”‚     └─ text: "Hello!"
   └─ element[1] [tagName="body"]
      └─ element[3] [tagName="h1"][properties={"id":"world"}]
         β”œβ”€ text: "World!"
         β”œβ”€ comment: "after"
         └─ element[0] [tagName="script"][properties={"src":"example.js","charSet":"UTF-8"}]

API

This package exports the following identifiers: fromDom. There is no default export.

fromDom(node)

Transform a DOM tree to a hast tree.

This works in a similar way to the parse5 version except that it works directly from the DOM rather than a string of HTML. Consequently, it does not maintain positional info.

Security

Use of hast-util-from-dom can open you up to a cross-site scripting (XSS) attack if the DOM is unsafe. Use hast-util-santize to make the hast tree safe.

Contribute

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.

License

ISC Β© Keith McKnight

Hast Util From Dom

utility to transform a DOM tree to hast

Hast Util From Dom Info

⭐ Stars13
πŸ”— Homepageunifiedjs.com
πŸ”— Source Codegithub.com
πŸ•’ Last Updatea year ago
πŸ•’ Created5 years ago
🐞 Open Issues1
βž— Star-Issue Ratio13
😎 Authorsyntax-tree