Skip to content

Commit d41bed3

Browse files
committed
Add HTML serialization recipe.
1 parent a02e3a0 commit d41bed3

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

README.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,50 @@ let foo = document.createElement('foo');
6060
foo.appendChild(document.createTextNode('Hello, World!'));
6161
document.body.appendChild(foo);
6262
```
63+
64+
65+
---
66+
67+
68+
## Recipe: Serialize to HTML
69+
70+
One task `undom` doesn't handle for you by default is HTML serialization. A proper implementation of this would be cumbersome to maintain and would rely heavily on getters and setters, which limits browser support. Below is a simple recipe for serializing an `undom` Element (Document, etc) to HTML.
71+
72+
73+
#### Small & in ES2015:
74+
75+
```js
76+
Element.prototype.toString = el => this.nodeType===3 ? enc(this.textContent) : (
77+
'<'+this.nodeName.toLowerCase() + this.attributes.map(attr).join('') + '>' +
78+
this.childNodes.map(serialize).join('') + '</'+this.nodeName.toLowerCase()+'>'
79+
);
80+
let attr = a => ` ${a.name}="${enc(a.value)}"`;
81+
let enc = s => s.replace(/[&'"<>]/g, a => `&#${a};`);
82+
```
83+
84+
85+
#### ES3 Version
86+
87+
This also does pretty-printing.
88+
89+
```js
90+
function serialize(el) {
91+
if (el.nodeType===3) return el.textContent;
92+
var name = String(el.nodeName).toLowerCase(),
93+
str = '<'+name,
94+
c, i;
95+
for (i=0; i<el.attributes.length; i++) {
96+
str += ' '+el.attributes[i].name+'="'+el.attributes[i].value+'"';
97+
}
98+
str += '>';
99+
for (i=0; i<el.childNodes.length; i++) {
100+
c = serialize(el.childNodes[i]);
101+
if (c) str += '\n\t'+c.replace(/\n/g,'\n\t');
102+
}
103+
return str + (c?'\n':'') + '</'+name+'>';
104+
}
105+
106+
function enc(s) {
107+
return s.replace(/[&'"<>]/g, function(a){ return `&#${a};` });
108+
}
109+
```

0 commit comments

Comments
 (0)