Skip to content

Instantly share code, notes, and snippets.

@greim
Created May 17, 2011 06:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greim/976029 to your computer and use it in GitHub Desktop.
Save greim/976029 to your computer and use it in GitHub Desktop.
Nice ascii-art DOM trees
/**
tree.js - nice ascii-art DOM trees
usage: tree(element[, options]);
example:
var s = tree(document.body,{
serialize: function(element){...}, // return a string representation such as "div#foo.bar"
filter: function(element){...} // return false for any nodes to not include in tree
});
console.log(s);
*/
var tree = (function(){
function ser(e){
if(e.nodeType===1){
var s = e.nodeName.toLowerCase();
if(e.id){s+='#'+e.id;}
if(e.className){s+='.'+e.className;}
return s;
} else if (e.nodeType===9) {
return 'DOCUMENT';
} else if (e.data) {
return '#text';
}
}
function isNode(e){
return e.nodeType===1 || e.nodeType===9 || (e.nodeType===3 && e.data && wspatt.test(e.data));
}
var wspatt = /\S/;
function converge(tNodes){
if(tNodes.length){
var txt = document.createTextNode(tNodes.map(function(t){
return t.data;
}).join(''));
return txt;
}else{
return null;
}
}
function getChildren(elmt, filter){
var cNodes = elmt.childNodes;
var children = [];
for(var i=0;i<cNodes.length;i++){
children.push(cNodes[i]);
}
children = children.filter(isNode).filter(filter);
var result = [];
var data = [];
for(var i=0;i<children.length;i++){
var e = children[i];
if(e.nodeType === 3){
data.push(e);
}else{
var tNode = converge(data);
if(tNode){
data.length = 0;
result.push(tNode);
}
result.push(e);
}
}
var tNode = converge(data);
if(tNode)result.push(tNode);
return result;
}
function makeTree(elmt, pstack, options, last){
pstack.push({elmt:elmt,last:last});
var str = pstack.map(function(o,i){
if(i===0){return;}
var cur=o.elmt===elmt;
return cur
? o.last ? '`-- ' : '|-- '
: o.last ? ' ' : '| '
;
}).join('');
str += options.serialize(elmt);
str += '\n';
var children = getChildren(elmt, options.filter);
var res = str + children.map(function(child, idx){
return makeTree(
child,
pstack,
options,
idx===children.length-1
);
}).join('');
pstack.pop();
return res;
}
return function(elmt, options){
options = options || {};
return makeTree(elmt, [], {
filter: options.filter || function(){return true;},
serialize: options.serialize || ser
}, true);
};
})();
@zcorpan
Copy link

zcorpan commented Apr 12, 2019

Do you have a license for this piece of code?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment