Created
February 2, 2016 18:25
-
-
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
This file contains hidden or 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
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