Last active
March 17, 2022 11:13
-
-
Save thesephist/9d507a41f9200a25227d68d29a309840 to your computer and use it in GitHub Desktop.
DOM TreeWalker API from Oak
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
{ | |
loop: loop | |
} := import('std') | |
// headingsList takes some container <div> and returns a list of all headings | |
// within that section of the page, in order | |
fn headingsList(div) { | |
walker := document.createTreeWalker( | |
div | |
NodeFilter.SHOW_ELEMENT | |
{ | |
acceptNode: fn(el) if el.tagName { | |
'H1', 'H2', 'H3', 'H4', 'H5', 'H6' -> NodeFilter.FILTER_ACCEPT | |
_ -> NodeFilter.FILTER_SKIP | |
} | |
} | |
) | |
headings := [] | |
with loop() fn(_, break) if el := walker.nextNode() { | |
? -> break(headings) | |
_ -> headings << { | |
level: int(el.tagName.1) | |
text: el.textContent | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment