Last active
September 7, 2017 09:26
-
-
Save tomm1996/8728be62123c22ea1786d014b99382c0 to your computer and use it in GitHub Desktop.
Recursive string search in DOM-Nodes using a generator
This file contains 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
/* | |
* @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