DOM Node to String Serializer

2.2.1 · maintenance · verified Sun Apr 19

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.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to serialize various DOM nodes (text, elements) and implement custom serialization logic using both event listeners and one-time functions.

const serialize = require('dom-serialize');

// Example 1: Serializing a text node
let textNode = document.createTextNode('Hello & <World>!');
console.log('Text Node:', serialize(textNode));

// Example 2: Serializing a DOM element with nested content
let bodyElement = document.createElement('body');
let strongElement = document.createElement('strong');
strongElement.appendChild(document.createTextNode('This is strong text.'));
bodyElement.appendChild(strongElement);
console.log('DOM Element:', serialize(bodyElement));

// Example 3: Custom serialization using the 'serialize' event
bodyElement.firstChild.addEventListener('serialize', function (event) {
  // Override the serialization for the 'strong' tag
  event.detail.serialize = '[CUSTOM-STRONG]';
}, false);
console.log('Custom Event Serialization:', serialize(bodyElement));

// Example 4: One-time custom serializer function
const customSerializedOutput = serialize(bodyElement, function (event) {
  if (event.serializeTarget === bodyElement.firstChild) {
    // For the first child (the 'strong' tag), output an ellipsis
    event.detail.serialize = '...';
  } else if (event.serializeTarget !== bodyElement) {
    // Prevent serialization of any other child elements if present
    event.preventDefault();
  }
});
console.log('One-time Function Serialization:', customSerializedOutput);

view raw JSON →