Skip to content

Instantly share code, notes, and snippets.

@leodutra
Last active November 11, 2022 15:45
Show Gist options
  • Save leodutra/692890a66d8d80829e743a181136d58c to your computer and use it in GitHub Desktop.
Save leodutra/692890a66d8d80829e743a181136d58c to your computer and use it in GitHub Desktop.
Get DOM elements by text content
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