Skip to content

Instantly share code, notes, and snippets.

@karataev
Created November 17, 2020 08:46
Show Gist options
  • Save karataev/60cbf5d8947ece64ce67fc6fc9e29cae to your computer and use it in GitHub Desktop.
Save karataev/60cbf5d8947ece64ce67fc6fc9e29cae to your computer and use it in GitHub Desktop.
Walk a DOM tree and log a tag or text content
function padding(depth) {
return new Array(depth).fill(' ').join('');
}
function walk(node, depth) {
if (node.nodeType === 1) {
console.log(padding(depth) + node.tagName);
let children = Array.from(node.childNodes);
children.forEach(item => walk(item, depth + 1));
} else if (node.nodeType === 3) {
let text = node.textContent.trim();
if (text) console.log(padding(depth) + text);
}
}
function walkTree(selector) {
let root = document.querySelector(selector);
walk(root, 0);
}
walkTree('#root');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment