Skip to content

Instantly share code, notes, and snippets.

@nlitwin
Last active September 22, 2019 19:20
Show Gist options
  • Save nlitwin/6e4958cc99644f111a8a978bc207e0f3 to your computer and use it in GitHub Desktop.
Save nlitwin/6e4958cc99644f111a8a978bc207e0f3 to your computer and use it in GitHub Desktop.
Search and Filter DOM nodes using createTreeWalker
function findNodes(options = {}) {
let node
const arr = []
const el = options.el || document.body
const filter = options.filter ? { acceptNode: options.filter } : null
const walk = document.createTreeWalker(el, NodeFilter.SHOW_ELEMENT, filter, false)
while(node = walk.nextNode()) {
arr.push(node)
}
return arr
}
// Example: find all nodes that have a width greater than 375px
findNodes({ filter: node => node.scrollWidth > 375 })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment