1 | dom-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 |
|
---|
9 | It'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 |
|
---|
20 | For custom serialization logic, a "serialize" event is dispatched on
|
---|
21 | every `Node` which event listeners can override the default behavior on by
|
---|
22 | setting the `event.detail.serialize` property to a String or other Node.
|
---|
23 |
|
---|
24 | The "serialize" event bubbles, so it could be a good idea to utilize
|
---|
25 | event delegation on a known root node that will be serialized.
|
---|
26 | Check the `event.serializeTarget` property to check which `Node` is
|
---|
27 | currently being serialized.
|
---|
28 |
|
---|
29 |
|
---|
30 | Installation
|
---|
31 | ------------
|
---|
32 |
|
---|
33 | ``` bash
|
---|
34 | $ npm install dom-serialize
|
---|
35 | ```
|
---|
36 |
|
---|
37 |
|
---|
38 | Example
|
---|
39 | -------
|
---|
40 |
|
---|
41 | ``` js
|
---|
42 | var serialize = require('dom-serialize');
|
---|
43 | var node;
|
---|
44 |
|
---|
45 | // works with Text nodes
|
---|
46 | node = document.createTextNode('foo & <bar>');
|
---|
47 | console.log(serialize(node));
|
---|
48 |
|
---|
49 |
|
---|
50 | // works with DOM elements
|
---|
51 | node = document.createElement('body');
|
---|
52 | node.appendChild(document.createElement('strong'));
|
---|
53 | node.firstChild.appendChild(document.createTextNode('hello'));
|
---|
54 | console.log(serialize(node));
|
---|
55 |
|
---|
56 |
|
---|
57 | // custom "serialize" event
|
---|
58 | node.firstChild.addEventListener('serialize', function (event) {
|
---|
59 | event.detail.serialize = 'pwn';
|
---|
60 | }, false);
|
---|
61 | console.log(serialize(node));
|
---|
62 |
|
---|
63 |
|
---|
64 | // you can also just pass a function in for a one-time serializer
|
---|
65 | console.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 | ```
|
---|
77 | foo & <bar>
|
---|
78 | <body><strong>hello</strong></body>
|
---|
79 | <body>pwn</body>
|
---|
80 | <body>…</body>
|
---|
81 | ```
|
---|