Skip to content

Instantly share code, notes, and snippets.

@JeremyRH
Last active April 17, 2017 17:35
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 JeremyRH/4bea3407a0fac1c20d89 to your computer and use it in GitHub Desktop.
Save JeremyRH/4bea3407a0fac1c20d89 to your computer and use it in GitHub Desktop.
function getElementsByText(text, rootNode = document.documentElement) {
const nodeIterator = document.createNodeIterator(
rootNode,
NodeFilter.SHOW_TEXT,
(node) => node.nodeValue.trim() === text ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT
);
const matchingElements = [];
let currentNode;
while (currentNode = nodeIterator.nextNode()) {
const parentElement = currentNode.parentElement;
if (parentElement) {
matchingElements.push(parentElement);
}
}
return matchingElements;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment