UNPKG

1.41 kBJavaScriptView Raw
1
2var KEBAB = /[A-Z\u00C0-\u00D6\u00D8-\u00DE]/g;
3
4function toKebabCase (string) {
5 return string.replace(KEBAB, function (match) {
6 return '-' + match.toLowerCase();
7 });
8}
9
10function toHtml (data) {
11 if (typeof data === 'string') {
12 return document.createTextNode(data);
13 } else {
14 var node = document.createElement(data.name);
15
16 var attributes = data.attributes;
17 if (attributes) {
18 for (var name in attributes) {
19 node.setAttribute(toKebabCase(name), attributes[name]);
20 }
21 }
22
23 var children = data.children;
24 if (children) {
25 if (children.constructor === Array) {
26 for (var i = 0, l = children.length; i < l; i++) {
27 node.appendChild(toHtml(children[i]));
28 }
29 } else {
30 node.appendChild(toHtml(children));
31 }
32 }
33
34 return node;
35 }
36}
37
38var h = {
39 name: 'fieldset',
40 attributes: {
41 jValue: 'value'
42 },
43 children: [
44 {
45 name: 'input',
46 attributes: {
47 jValue: 'foo.poo'
48 }
49 },
50 {
51 name: 'input',
52 attributes: {
53 jValue: 'bar.dar'
54 }
55 },
56 {
57 name: 'div',
58 children: 'hello world'
59 }
60 ]
61};
62
63console.log(toHtml(h));