Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function html2json(subj) {
- "use strict";
- if (typeof subj == "string") {
- var x = document.createElement("DIV");
- x.innerHTML=subj;
- var res = html2json(x);
- return res["@"];
- } else {
- var res = {};
- res["#"] = subj.tagName;
- var attrs = subj.attributes
- Array.prototype.forEach.call(attrs, x=>{
- res[x.name] = x.value;
- });
- var x = subj.firstChild;
- var a = [];
- while (x) {
- if (x.nodeType == Node.TEXT_NODE) {
- a.push(x.nodeValue);
- } else {
- a.push(html2json(x));
- }
- x = x.nextSibling;
- }
- res["@"] = a;
- return res;
- }
- }
- function json2html(subj) {
- "use strict";
- if (Array.isArray(subj)) {
- return subj.reduce(
- (a,b)=>{
- a.appendChild(json2html(b));
- return a;
- },document.createDocumentFragment());
- } else if (typeof subj == "object") {
- var el = document.createElement(subj['#']);
- for (var z in subj) {
- if (z == '#') continue;
- else if (z == '@') el.appendChild(json2html(subj[z]));
- else {
- el.setAttribute(z, subj[z]);
- }
- }
- return el;
- } else {
- var z = document.createTextNode(subj);
- return z;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment