Skip to content

Instantly share code, notes, and snippets.

@HunterLarco
Last active August 9, 2020 03:00
Show Gist options
  • Save HunterLarco/e028b702dfbc776905b6a8ae9a072077 to your computer and use it in GitHub Desktop.
Save HunterLarco/e028b702dfbc776905b6a8ae9a072077 to your computer and use it in GitHub Desktop.
function isIgnoredNode(node) {
if (node.nodeName == 'NOSCRIPT') {
return true;
}
return false;
}
function* nodeIterator(root) {
const treeWalker = document.createTreeWalker(
root,
NodeFilter.SHOW_ALL,
{
acceptNode(node) {
return isIgnoredNode(node)
? NodeFilter.FILTER_REJECT
: NodeFilter.FILTER_ACCEPT;
},
}
);
let node = treeWalker.currentNode;
while (node) {
yield node;
node = treeWalker.nextNode();
}
}
export default function* walk(selection) {
const startContainer = selection.startContainer;
const startOffset = selection.startOffset;
const endContainer = selection.endContainer;
const endOffset = selection.endOffset;
if (startContainer === endContainer && startOffset == endOffset) {
return null;
}
if (!startContainer.childNodes.length) {
yield startContainer
}
if (startContainer === endContainer) {
return;
}
let ancestor = startContainer;
while (ancestor) {
let sibling = ancestor;
while (sibling.nextSibling) {
sibling = sibling.nextSibling;
for (const node of nodeIterator(sibling)) {
if (!node.childNodes.length) {
yield node
}
if (node === endContainer) {
return
}
}
}
ancestor = ancestor.parentNode;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment