Created
November 17, 2020 08:46
-
-
Save karataev/60cbf5d8947ece64ce67fc6fc9e29cae to your computer and use it in GitHub Desktop.
Walk a DOM tree and log a tag or text content
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
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