dom-serialize is a JavaScript library designed to convert various types of DOM nodes into an HTML string representation. Unlike the standard `outerHTML` property, it provides robust serialization capabilities for a broader range of DOM entities, including DOM elements, text nodes, attribute nodes, comment nodes, documents, document fragments, doctypes, NodeLists, and arrays of nodes. The current stable version is 2.2.1, released approximately 10 years ago, suggesting a mature and stable, though not actively developed, state. A key differentiator is its extensible serialization logic through a custom 'serialize' event, allowing developers to intercept and override default serialization for specific nodes or even use a one-time serializer function. This provides fine-grained control over the output, making it suitable for scenarios requiring custom HTML generation or specific content filtering. It supports both browser and Node.js environments, though Node.js usage requires a virtual DOM implementation.
npm install dom-serializeVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to serialize various DOM nodes (text, elements) and implement custom serialization logic using both event listeners and one-time functions.
When using the 'serialize' event, always check `event.serializeTarget` against the specific node you intend to customize, or use `event.stopPropagation()` if appropriate, to prevent unintended overrides.
Correct the typo in `event.detail.serialze` to `event.detail.serialize` when providing custom serialization values.
In Node.js, use a library such as `jsdom` to set up a virtual DOM environment before creating or manipulating DOM nodes that `dom-serialize` will process.
Assess the suitability of this library for new projects requiring active maintenance or modern browser/Node.js features. Consider alternatives like `@quatico/dom-serializer` or `dom-serializer` (from CheerioJS) if active development, ESM support, or specific features like Shadow DOM serialization are needed.
Install and configure a virtual DOM library like `jsdom`. For example: `const { JSDOM } = require('jsdom'); const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>'); global.document = dom.window.document;`For ES Modules, use `import serialize from 'dom-serialize';`. For CommonJS, use `const serialize = require('dom-serialize');` to correctly import the default function.No dependency data recorded yet.