CSS is made for styling. Use JS to add the class to your HTML element.
The Function:
Pass the string to search for and the selector/s to search, in my case I am searching all tags in the DOM and returning an array [...document.getElementsByTagName('*')].
We define an array to hold the non-restricted elements we want to search and another that holds the restricted tags we want to skip. We then loop the output array with !restricted.includes(tag.nodeName.toLowerCase(), this checks to see if our restricted array does not include an element from our DOM query. For the elements that return true, we push them into our output array --> output.push(tag)
Once we have our output array filled with the tags we want to search, we search the tag for our string --> tag.innerText.includes(string) and VERY IMPORTANT: !(tag.textContent.match(/\n/g)||[]).length will make sure it is the right child node, if this returns true, we replace the tags innerHTML and simply wrap our string with span tags that now contain a class that is styled as we want it to be styled -->
tag.innerHTML = tag.innerText.replace(string, `<span class="red">${string}</span>`)
const els = [...document.getElementsByTagName('*')] const string = "Hello" function Change(string, els) { const restricted = ['html', 'body', 'head', 'style', 'meta', 'script'] const output = [] els.forEach(tag => !restricted.includes(tag.nodeName.toLowerCase()) ? output.push(tag) : null) output.forEach(tag => tag.innerText.includes(string) && !(tag.textContent.match(/\n/g) || []).length ? tag.innerHTML = tag.innerText.replace(string, `<span class="red">${string}</span>`) : null) } Change(string, els)
.red { color: red; }
<p id="p1">Hello World!</p> <div>Hello World...</div> <div> <ul> <li>Hello World.</li> </ul> </div> <p> <a href="#">Hello <span>World</span></a> </p> <table border="1"> <tr> <th>Hello</th><th>World</th> </tr> <tr> <td>World</td><td>Hello</td> </tr> </table>