You'll have to traverse the Text Nodes this way:
const walkTextNodes = (node, filter) => {
const result = [];
const execute = node => {
let child = node.firstChild;
while (child) {
switch (child.nodeType) {
case Node.TEXT_NODE:
if (child.textContent.indexOf(filter) > -1 ){
result.push(child.parentNode);
}
break;
case Node.ELEMENT_NODE:
execute(child);
break;
}
child = child.nextSibling;
}
}
if (node) {
execute(node);
}
return result;
}
const elementsFound = walkTextNodes(rootElement, "CORRECT-TEXT");
console.log( elementsFound[0] );
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:
function contains( selector, text ){
const elements = document.querySelectorAll(selector);
return Array.prototype.filter.call(elements, function(element){
if (RegExp(text).test(element.firstChild.textContent)) {
return element;
}
});
}
console.log(contains('div', 'CORRECT-TEXT')[0]);
Working Demo:
const walkTextNodes = (node, filter) => {
const result = [];
const execute = node => {
let child = node.firstChild;
while (child) {
switch (child.nodeType) {
case Node.TEXT_NODE:
if (child.textContent.indexOf(filter) > -1 ){
result.push(child.parentNode);
}
break;
case Node.ELEMENT_NODE:
execute(child);
break;
}
child = child.nextSibling;
}
}
if (node) {
execute(node);
}
return result;
}
const elementsFound = walkTextNodes(rootElement, "CORRECT-TEXT");
console.log( elementsFound[0] );
// Take 2
function contains( selector, text ){
const elements = document.querySelectorAll(selector);
return Array.prototype.filter.call(elements, function(element){
if (RegExp(text).test(element.firstChild.textContent)) {
return element;
}
});
}
console.log(contains('div', 'CORRECT-TEXT')[0]);
<div id="rootElement">othertext
<div>othertext
<div>othertext
<div>othertext
<div>othertext CORRECT-TEXT othertext</div>
</div>othertext
</div>othertext
</div>othertext
</div>othertext