I’m trying to find an element in a page that does not have id’s or classes. The only way is by certain specific text that it’s contained in the div. I Found this function but it selects all the parent nodes, not only the inner child. (for obvious reasons because all the nested divs contains that text). How can I modify the function to select ONLY the div who directly have the searched text and excluding the search in children nodes?
Thanks for the help!
function contains(selector, text) {
var elements = document.querySelectorAll(selector);
return Array.prototype.filter.call(elements, function(element){
return RegExp(text).test(element.textContent);
});
}
console.log(contains('div', 'CORRECT-TEXT'));
<div>othertext
<div>othertext
<div>othertext
<div>othertext
<div>othertext CORRECT-TEXT othertext</div>
</div>othertext
</div>othertext
</div>othertext
</div>othertext
2
Answers
You’ll have to traverse the Text Nodes this way:
Once you find a text node containing the text you’re looking for, check the parentElement and push it into the
result
array.The code needs some testing and depending on your use case, it might require some tweaks, e.g. to return the first element or all the elements found with the keyword, etc. but I thinks it’s a good start.
Update: here’s a refactoring of the original
contains
function that produces the same result:Working Demo:
A simpler and more functional approach, see if it helps in solving your problem