Created
October 22, 2020 08:04
-
-
Save tsmd/e7fa28b3f08999d5fd1ba3b8d480bf2a to your computer and use it in GitHub Desktop.
DOM utilities
This file contains 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 getFirstTextNode(root) { | |
return traverse(root, (node) => node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== ""); | |
} | |
/** | |
* ツリー上で最後に登場するテキストノードを深さ優先で探索し取得する | |
*/ | |
function getLastTextNode(root) { | |
return traverse(root, (node) => node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== "", true); | |
} | |
function traverse(rootNode, predicate, reverse = false) { | |
const length = rootNode.childNodes.length; | |
const init = reverse ? length - 1 : 0; | |
const cond = (i) => reverse ? i >= 0 : i < length; | |
const increment = reverse ? -1 : 1; | |
if (predicate(rootNode)) { | |
return rootNode; | |
} | |
for (let i = init; cond(i); i += increment) { | |
const deep = traverse(rootNode.childNodes[i], predicate, reverse); | |
if (deep !== null) { | |
return deep; | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment