Skip to content

Instantly share code, notes, and snippets.

@sanjeevsubedi
Created February 20, 2023 22:44
Show Gist options
  • Save sanjeevsubedi/7d7f6cc21468d5c0d621e57edd887d69 to your computer and use it in GitHub Desktop.
Save sanjeevsubedi/7d7f6cc21468d5c0d621e57edd887d69 to your computer and use it in GitHub Desktop.
Find the DOM element by the matching text content recursively.
function getSelectorByText(
node: HTMLElement,
text: string
): HTMLElement | undefined {
if (node?.innerHTML?.trim() === text) {
return node;
}
for (let i = 0; i < node.children.length; i++) {
const found = getSelectorByText(node.children[i] as HTMLElement, text);
if (found) {
return found;
}
}
return undefined;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment