Skip to content

Instantly share code, notes, and snippets.

@thesephist
Last active March 17, 2022 11:13
Show Gist options
  • Save thesephist/9d507a41f9200a25227d68d29a309840 to your computer and use it in GitHub Desktop.
Save thesephist/9d507a41f9200a25227d68d29a309840 to your computer and use it in GitHub Desktop.
DOM TreeWalker API from Oak
{
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