UNPKG

2.06 kBMarkdownView Raw
1dom-serialize
2=============
3### Serializes any DOM node into a String
4
5[![Sauce Test Status](https://saucelabs.com/browser-matrix/dom-serialize.svg)](https://saucelabs.com/u/dom-serialize)
6
7[![Build Status](https://travis-ci.org/webmodules/dom-serialize.svg?branch=master)](https://travis-ci.org/webmodules/dom-serialize)
8
9It's like `outerHTML`, but it works with:
10
11 * DOM elements
12 * Text nodes
13 * Attributes
14 * Comment nodes
15 * Documents
16 * DocumentFragments
17 * Doctypes
18 * NodeLists / Arrays
19
20For custom serialization logic, a "serialize" event is dispatched on
21every `Node` which event listeners can override the default behavior on by
22setting the `event.detail.serialize` property to a String or other Node.
23
24The "serialize" event bubbles, so it could be a good idea to utilize
25event delegation on a known root node that will be serialized.
26Check the `event.serializeTarget` property to check which `Node` is
27currently being serialized.
28
29
30Installation
31------------
32
33``` bash
34$ npm install dom-serialize
35```
36
37
38Example
39-------
40
41``` js
42var serialize = require('dom-serialize');
43var node;
44
45// works with Text nodes
46node = document.createTextNode('foo & <bar>');
47console.log(serialize(node));
48
49
50// works with DOM elements
51node = document.createElement('body');
52node.appendChild(document.createElement('strong'));
53node.firstChild.appendChild(document.createTextNode('hello'));
54console.log(serialize(node));
55
56
57// custom "serialize" event
58node.firstChild.addEventListener('serialize', function (event) {
59 event.detail.serialize = 'pwn';
60}, false);
61console.log(serialize(node));
62
63
64// you can also just pass a function in for a one-time serializer
65console.log(serialize(node, function (event) {
66 if (event.serializeTarget === node.firstChild) {
67 // for the first child, output an ellipsis to summarize "content"
68 event.detail.serialze = '…';
69 } else if (event.serializeTarget !== node) {
70 // any other child
71 event.preventDefault();
72 }
73}));
74```
75
76```
77foo &amp; &lt;bar&gt;
78<body><strong>hello</strong></body>
79<body>pwn</body>
80<body>…</body>
81```