Last active
November 11, 2022 15:45
-
-
Save leodutra/692890a66d8d80829e743a181136d58c to your computer and use it in GitHub Desktop.
Get DOM elements by text content
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
const getElementsByText = (text, parent) => { | |
if (!text) return [] | |
const xpath = `//*[text()='${text}']` | |
const xpathResult = document.evaluate( | |
xpath, | |
parent || document, | |
null, | |
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, | |
null | |
) | |
const results = [] | |
for (let i = 0, length = xpathResult.snapshotLength; i < length; ++i) { | |
results.push(xpathResult.snapshotItem(i)) | |
} | |
return results | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment