dom-serialize
Serializes any DOM node into a String
It's like outerHTML
, but it works with:
- DOM elements
- Text nodes
- Attributes
- Comment nodes
- Documents
- DocumentFragments
- Doctypes
- NodeLists / Arrays
For custom serialization logic, a "serialize" event is dispatched on
every Node
which event listeners can override the default behavior on by
setting the event.detail.serialize
property to a String or other Node.
Installation
$ npm install dom-serialize
Example
var serialize = require('dom-serialize');
var node;
node = document.createTextNode('foo & <bar>');
console.log(serialize(node));
node = document.createElement('body');
node.appendChild(document.createElement('strong'));
node.firstChild.appendChild(document.createTextNode('hello'));
console.log(serialize(node));
node.firstChild.addEventListener('serialize', function (event) {
event.detail.serialize = 'pwn';
}, false);
console.log(serialize(node));
console.log(serialize(node, function (event) {
if (event.target === node.firstChild) {
event.detail.serialze = '…';
} else if (event.target !== node) {
event.preventDefault();
}
}));
foo & <bar>
<body><strong>hello</strong></body>
<body>pwn</body>
<body>…</body>