1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | module.exports = parse;
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | var map = {
|
13 | legend: [1, '<fieldset>', '</fieldset>'],
|
14 | tr: [2, '<table><tbody>', '</tbody></table>'],
|
15 | col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'],
|
16 | _default: [0, '', '']
|
17 | };
|
18 |
|
19 | map.td =
|
20 | map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
|
21 |
|
22 | map.option =
|
23 | map.optgroup = [1, '<select multiple="multiple">', '</select>'];
|
24 |
|
25 | map.thead =
|
26 | map.tbody =
|
27 | map.colgroup =
|
28 | map.caption =
|
29 | map.tfoot = [1, '<table>', '</table>'];
|
30 |
|
31 | map.text =
|
32 | map.circle =
|
33 | map.ellipse =
|
34 | map.line =
|
35 | map.path =
|
36 | map.polygon =
|
37 | map.polyline =
|
38 | map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>'];
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 | function parse(html) {
|
49 | if ('string' != typeof html) throw new TypeError('String expected');
|
50 |
|
51 |
|
52 | var m = /<([\w:]+)/.exec(html);
|
53 | if (!m) return document.createTextNode(html);
|
54 |
|
55 | html = html.replace(/^\s+|\s+$/g, '');
|
56 |
|
57 | var tag = m[1];
|
58 |
|
59 |
|
60 | if (tag == 'body') {
|
61 | var el = document.createElement('html');
|
62 | el.innerHTML = html;
|
63 | return el.removeChild(el.lastChild);
|
64 | }
|
65 |
|
66 |
|
67 | var wrap = map[tag] || map._default;
|
68 | var depth = wrap[0];
|
69 | var prefix = wrap[1];
|
70 | var suffix = wrap[2];
|
71 | var el = document.createElement('div');
|
72 | el.innerHTML = prefix + html + suffix;
|
73 | while (depth--) el = el.lastChild;
|
74 |
|
75 |
|
76 | if (el.firstChild == el.lastChild) {
|
77 | return el.removeChild(el.firstChild);
|
78 | }
|
79 |
|
80 |
|
81 | var fragment = document.createDocumentFragment();
|
82 | while (el.firstChild) {
|
83 | fragment.appendChild(el.removeChild(el.firstChild));
|
84 | }
|
85 |
|
86 | return fragment;
|
87 | }
|