Skip to content

Instantly share code, notes, and snippets.

@tomm1996
Last active September 7, 2017 09:26
Show Gist options
  • Save tomm1996/8728be62123c22ea1786d014b99382c0 to your computer and use it in GitHub Desktop.
Save tomm1996/8728be62123c22ea1786d014b99382c0 to your computer and use it in GitHub Desktop.
Recursive string search in DOM-Nodes using a generator
/*
* @param {HTMLElement} node
* @yields {Iterable.<*>}
*/
function* _deepTraverseElements (node) {
if (node.nodeType !== 1) {
return;
}
for (let i = 0; i < node.children.length; i++) {
yield* _deepTraverseElements(node.children[i]);
}
yield node;
}
/*
* Usage: findElementByInnerText('body', 'Hello World');
* @param {string} selector
* @param {string} String the element should contain
* @returns {(boolean)|(HTMLElement)} DOM-Element that contains the string. Returns false if none is found
*/
const findElementByInnerText = (selector, text) => {
const node = document.querySelector(selector);
_deepTraverseElements(parent);
for (const element of _deepTraverseElements(node)) {
if (element.textContent.includes(text)) {
return element;
}
}
return false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment