0

I'm trying to replace some words in DOM with chrome extension. While the hard coded word works and is replaced, I don't know how to do it dynamically, e.g. to loop through several words and if any of them is on web page, it should be used as a variable and replaced on page. Since I'm a n00b (obviously), I hope I'm making sense.

Here's the code:

const Key = ('covid-19', 'coronavirus', 'covid'); // TODO: use this as a variable in innerhtml below

const words = document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, td, caption, span');

let div = document.createElement('div');
div.id = 'tag';
let text = document.createTextNode('TAG');

for(let i = 0; i < words.length; i++){
    if(words[i].innerHTML.includes('COVID-19')|| words[i].innerHTML.includes('COVID-19')){
       words[i].innerHTML = words[i].innerHTML.replace('COVID-19', '<a href="https://www.cdc.gov/">ALERT</a>');
       div.appendChild(text);
}

Thanks!

  • See [Javascript .replace command replace page text?](https://stackoverflow.com/a/7275856) and [Replace multiple strings with multiple other strings](https://stackoverflow.com/q/15604140) – wOxxOm Sep 08 '22 at 11:26
  • Thanks, I looked into those, but it seems it's not working when trying to replace words with links. – bostjan jaro Sep 09 '22 at 02:30
  • You would need another example: [Highlight word in HTML text (but not markup)](https://stackoverflow.com/a/10730063) BTW all of this should be possible by using `mark.js` library. – wOxxOm Sep 09 '22 at 05:20
  • not a clue on how to convert the highlightning code into my own purpose, so I'll give it a pass, sorry:) I've searched everywhere on SO for my solution, but no luck. It would be great to have just a func to do as I need, nothing complicated. – bostjan jaro Sep 09 '22 at 08:26

0 Answers0