Skip to content

Instantly share code, notes, and snippets.

@karataev
Created November 17, 2020 08:46

Revisions

  1. karataev created this gist Nov 17, 2020.
    21 changes: 21 additions & 0 deletions walkTree.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    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');