Skip to content

Instantly share code, notes, and snippets.

@bitsmanent
Last active June 9, 2017 16:53
Show Gist options
  • Save bitsmanent/59255aa653d9d7e8e73241f35b5c70fa to your computer and use it in GitHub Desktop.
Save bitsmanent/59255aa653d9d7e8e73241f35b5c70fa to your computer and use it in GitHub Desktop.
Build an emmet string from actual DOM
/* Sample usage: html2zc(document.documentElement); */
(function() {
"use strict";
function parse(node, code) {
var chld = [], i, nc, c;
if(skipnode(node))
return;
code += tozc(node);
nc = node.childNodes.length;
if(!nc)
return code;
for(i = 0; i < nc; ++i) {
c = node.childNodes[i];
if(skipnode(c))
continue;
if(c.nodeType == 3) {
if(trim(c.nodeValue))
chld.push('{'+sanitize(c.nodeValue)+'}')
}
else
chld.push(parse(c, ""));
}
if(nc == 1 && node.childNodes[0].nodeType == 3)
code += chld[0];
else
code += '>'+chld.join('+');
return code;
}
function skipnode(node) {
return node.nodeType == 8 || (node.nodeType == 1 && (
node.tagName.toLowerCase() == "style"
|| node.tagName.toLowerCase() == "script"
));
}
function sanitize(nodeval) {
return nodeval.replace(/\n/g, '\\n');
}
function tozc(node) {
var code = "", t, len, i, tag;
tag = node.tagName.toLowerCase();
if(tag != "div")
code += tag;
t = node.getAttribute("id");
if(t)
code += '#'+t;
for(i = 0, len = node.classList.length; i < len; ++i)
code += '.'+node.classList[i];
return code;
}
function trim(s) {
return s.replace(/^([ \t\n]*)/, "").replace(/([ \t\n]*)$/, "");
}
function main(node) {
return parse(node, "");
}
window.html2zc = main;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment