Skip to content

Instantly share code, notes, and snippets.

@mityukov
Created February 2, 2016 18:25
Show Gist options
  • Save mityukov/e72388f60c79dd93c6a1 to your computer and use it in GitHub Desktop.
Save mityukov/e72388f60c79dd93c6a1 to your computer and use it in GitHub Desktop.
JavaScript: findElementContains(elmName, needle) -- a function, allowing to find the deepest HTML element of given tag name, containing the text node with given text
function findElementContains(elmName, needle) {
var foundTextNode = null;
var allElms = document.querySelectorAll("*");
for (var i=0; i < allElms.length; i++) {
var allChildren = allElms[i].childNodes;
for (var j=0; j < allChildren.length; j++) {
if (allChildren[j].nodeType == 3 && allChildren[j].nodeValue.indexOf(needle) > -1) { // text node
foundTextNode = allChildren[j];
break;
}
}
}
if (foundTextNode) {
var nextParent = foundTextNode.parentNode;
while(nextParent) {
if (nextParent.tagName.toLowerCase()==elmName.toLowerCase()) {
return nextParent;
}
nextParent = nextParent.parentNode;
}
}
return undefined;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment