The reason I need the class name is because my future plan is to place an image over the div that contains the words in my array.
It sounds like you want to get a reference to the div
, not its class (but once you have a reference to it, you can get its class from .className
if you really need it).
That means rather than using innerText
, you'll need to walk the nodes in the document tree, which is quite straightforward. For this answer I posted a general-purpose "find matching nodes in the DOM" function that accepts a predicate function, so we can use it with a predicate tht checks the text nodes in the element for the words in the array.
You've used Array#every
in your question, which will only return true
if all the iterations returned a truthy value; below I've used Array#some
to flag up having found any of them instead. Elements containing any of the words get a class added to them, highlight
, which puts a yellow background behind them:
// The searcher function
function domFind(element, predicate, results = []) {
if (!element.children) {
throw new Error("Starting node must be an element or document");
}
if (predicate(element)) {
results.push(element);
}
if (element.children && element.children.length) {
[...element.children].forEach(child => {
domFind(child, predicate, results);
});
}
return results;
}
// Our words
let array = ["terrible", "but", "pasta"];
// Do our search with a predicate
let elements = domFind(document, element => {
return Array.from(element.childNodes).some(n => {
return n.nodeName.toLowerCase() != "script" &&
n.nodeType == 3 &&
array.some(word => n.nodeValue.indexOf(word) != -1);
});
});
// We have the array of elements; add a class to them
elements.forEach(e => { e.classList.add("highlight"); });
.highlight {
background-color: yellow;
}
<div>blah blah</div>
<div>this is terrible!</div>
<div>lorem ipsum</div>
<div>
<div>
<div>no fate but what we make</div>
</div>
<div>la la la</div>
<div>mmmmmm pasta</div>
</div>
<div>foo</div>
Since this is for a Chrome extension, I've happily used ES2015 for the above.