Skip to content

Instantly share code, notes, and snippets.

@tsmd
Created October 22, 2020 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsmd/e7fa28b3f08999d5fd1ba3b8d480bf2a to your computer and use it in GitHub Desktop.
Save tsmd/e7fa28b3f08999d5fd1ba3b8d480bf2a to your computer and use it in GitHub Desktop.
DOM utilities
/**
* ツリー上で最初に登場するテキストノードを深さ優先で探索し取得する
*/
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