Skip to content

Instantly share code, notes, and snippets.

@gilbertoalbino
Last active March 14, 2020 12:18
Show Gist options
  • Save gilbertoalbino/e22dbb0019ec269fa21d64534599e392 to your computer and use it in GitHub Desktop.
Save gilbertoalbino/e22dbb0019ec269fa21d64534599e392 to your computer and use it in GitHub Desktop.
Prototype for extending HTMLElement capabilities of finding node by text
HTMLElement.prototype.getElementsByInnerText = function (text, escape) {
var nodes = this.querySelectorAll("*");
var matches = [];
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].innerText == text) {
matches.push(nodes[i]);
}
}
if (escape) {
return matches;
}
var result = [];
for (var i = 0; i < matches.length; i++) {
var filter = matches[i].getElementsByInnerText(text, true);
if (filter.length == 0) {
result.push(matches[i]);
}
}
return result;
};
document.getElementsByInnerText = HTMLElement.prototype.getElementsByInnerText;
HTMLElement.prototype.getElementByInnerText = function (text) {
var result = this.getElementsByInnerText(text);
if (result.length == 0) return null;
return result[0];
}
document.getElementByInnerText = HTMLElement.prototype.getElementByInnerText;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment