UNPKG

1.8 kBJavaScriptView Raw
1
2/**
3 * Expose `parse`.
4 */
5
6module.exports = parse;
7
8/**
9 * Wrap map from jquery.
10 */
11
12var 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
19map.td =
20map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>'];
21
22map.option =
23map.optgroup = [1, '<select multiple="multiple">', '</select>'];
24
25map.thead =
26map.tbody =
27map.colgroup =
28map.caption =
29map.tfoot = [1, '<table>', '</table>'];
30
31map.text =
32map.circle =
33map.ellipse =
34map.line =
35map.path =
36map.polygon =
37map.polyline =
38map.rect = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>'];
39
40/**
41 * Parse `html` and return the children.
42 *
43 * @param {String} html
44 * @return {Array}
45 * @api private
46 */
47
48function parse(html) {
49 if ('string' != typeof html) throw new TypeError('String expected');
50
51 // tag name
52 var m = /<([\w:]+)/.exec(html);
53 if (!m) return document.createTextNode(html);
54
55 html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace
56
57 var tag = m[1];
58
59 // body support
60 if (tag == 'body') {
61 var el = document.createElement('html');
62 el.innerHTML = html;
63 return el.removeChild(el.lastChild);
64 }
65
66 // wrap map
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 // one element
76 if (el.firstChild == el.lastChild) {
77 return el.removeChild(el.firstChild);
78 }
79
80 // several elements
81 var fragment = document.createDocumentFragment();
82 while (el.firstChild) {
83 fragment.appendChild(el.removeChild(el.firstChild));
84 }
85
86 return fragment;
87}