Last active
June 9, 2017 16:53
-
-
Save bitsmanent/59255aa653d9d7e8e73241f35b5c70fa to your computer and use it in GitHub Desktop.
Build an emmet string from actual DOM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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