hast-util-from-dom

5.0.1 · active · verified Sun Apr 19

hast-util-from-dom is a utility package designed to convert a DOM tree (either from a browser's native DOM or headless environments like JSDOM) into a HAST (Hypertext Abstract Syntax Tree) HTML syntax tree. It is part of the unified ecosystem for processing text. The current stable version is 5.0.1, which is ESM-only and requires Node.js 16 or newer. It typically follows the release cadence of the wider unified ecosystem. Key differentiators include its small size, primary suitability for browser environments, and its explicit choice *not* to provide positional information, which distinguishes it from more comprehensive parsing solutions. It serves as the inverse to `hast-util-to-dom` and is wrapped by `rehype-dom-parse` for HTML parsing with DOM APIs. While efficient for its purpose, users should be aware that it might yield varying results in different or older browsers.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates converting a DOM element (from JSDOM in Node.js) into a HAST tree.

import { fromDom } from 'hast-util-from-dom';
import { JSDOM } from 'jsdom';

const htmlContent = `
  <!doctype html>
  <title>Example</title>
  <body>
    <main>
      <h1>Hi</h1>
      <p><em>Hello</em>, world!</p>
    </main>
  </body>
`;

const dom = new JSDOM(htmlContent);
const document = dom.window.document;

// Select an element from the simulated DOM
const mainElement = document.querySelector('main');

if (mainElement) {
  // Transform the DOM element into a hast tree
  const hast = fromDom(mainElement);

  // Log the resulting hast tree structure
  console.log(JSON.stringify(hast, null, 2));
} else {
  console.error('Main element not found in the DOM.');
}

view raw JSON →