forked from philipmulcahy/azad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dom2json.js
83 lines (80 loc) · 2.34 KB
/
dom2json.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Thanks to Simon Sturmer: sstur/dom-to-json.js
const dom2json = (() => {
function toJSON(node) {
node = node || this;
var obj = {
nodeType: node.nodeType
};
if (node.tagName) {
obj.tagName = node.tagName.toLowerCase();
} else
if (node.nodeName) {
obj.nodeName = node.nodeName;
}
if (node.nodeValue) {
obj.nodeValue = node.nodeValue;
}
var attrs = node.attributes;
if (attrs) {
var length = attrs.length;
var arr = obj.attributes = new Array(length);
for (var i = 0; i < length; i++) {
attr = attrs[i];
arr[i] = [attr.nodeName, attr.nodeValue];
}
}
var childNodes = node.childNodes;
if (childNodes) {
length = childNodes.length;
arr = obj.childNodes = new Array(length);
for (i = 0; i < length; i++) {
arr[i] = toJSON(childNodes[i]);
}
}
return obj;
}
function toDOM(obj) {
if (typeof obj == 'string') {
obj = JSON.parse(obj);
}
var node, nodeType = obj.nodeType;
switch (nodeType) {
case 1: //ELEMENT_NODE
node = document.createElement(obj.tagName);
var attributes = obj.attributes || [];
for (var i = 0, len = attributes.length; i < len; i++) {
var attr = attributes[i];
node.setAttribute(attr[0], attr[1]);
}
break;
case 3: //TEXT_NODE
node = document.createTextNode(obj.nodeValue);
break;
case 8: //COMMENT_NODE
node = document.createComment(obj.nodeValue);
break;
case 9: //DOCUMENT_NODE
node = document.implementation.createDocument();
break;
case 10: //DOCUMENT_TYPE_NODE
node = document.implementation.createDocumentType(obj.nodeName);
break;
case 11: //DOCUMENT_FRAGMENT_NODE
node = document.createDocumentFragment();
break;
default:
return node;
}
if (nodeType == 1 || nodeType == 11) {
var childNodes = obj.childNodes || [];
for (i = 0, len = childNodes.length; i < len; i++) {
node.appendChild(toDOM(childNodes[i]));
}
}
return node;
}
return {
toJSON: toJSON,
toDOM: toDOM,
};
})();