Skip to content

Instantly share code, notes, and snippets.

@matthewp
Created October 26, 2018 12:55
Show Gist options
  • Save matthewp/06b05aedc9221db1c0606974be8811e8 to your computer and use it in GitHub Desktop.
Save matthewp/06b05aedc9221db1c0606974be8811e8 to your computer and use it in GitHub Desktop.
Print the document, for debugging
function printDocument(node, startIndex = 0) {
let skip, tmp;
let depth = 0;
let index = startIndex;
let items = [];
function add(node) {
let str = index + "-" + node.nodeName;
items.push(str);
}
// Always start with the initial element.
do {
if ( !skip && (tmp = node.firstChild) ) {
depth++;
add(tmp);
index++;
} else if ( tmp = node.nextSibling ) {
skip = false;
add(tmp);
index++;
} else {
// Skipped or no first child and no next sibling, so traverse upwards,
tmp = node.parentNode;
// and decrement the depth.
depth--;
// Enable skipping, so that in the next loop iteration, the children of
// the now-current node (parent node) aren't processed again.
skip = true;
}
// Instead of setting node explicitly in each conditional block, use the
// tmp var and set it here.
node = tmp;
// Stop if depth comes back to 0 (or goes below zero, in conditions where
// the passed node has neither children nore next siblings).
} while ( depth > 0 );
console.log(items.join("|"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment