-1

Edit: Should have said, this is for a Greasemonkey script, so it's basically to highlight a number of key phrases on a specific set of HTML pages. Thanks

This code highlights "First Phrase" in yellow:

document.body.innerHTML= document.body.innerHTML.replace(/First Phrase/g, function(m){
return '<span style="background-color:yellow">'+m+'</span>';
});

But how can I highlight multiple phrases in different colours, e.g. "Second Phrase" in red, "Third Phrase" in blue, and so on.

Thanks

huey
  • 115
  • 9
  • 4
    I hope you realise that serialising the de-serialising the entire body will destroy dynamically established relationships like listeners, live collections, etc. Also, you should [*not attempt to parse HTML with a regular expression*](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). – RobG Aug 01 '17 at 04:08
  • Do you have multiple different regular expressions to match the different phrases? If so, you can just repeat the code shown for each phrase (though then you don't need a function as the second argument of `.replace()`). – nnnnnn Aug 01 '17 at 04:14
  • @Shomz it seems to me he is trying to modify the entire HTML for the entire page and not just an array like the question you have duped it as. – Lime Aug 01 '17 at 04:15
  • @nnnnnn - thanks, how do I repeat the code without the function? I did try this - JS noob - but keep getting stuck. – huey Aug 01 '17 at 04:42

3 Answers3

0

First, create an array of colours that you would like to use for your elements.

Second, collect all of the target elements with your favourite collection method of choice. I'm using getElementsByTagName in my example.

Third, create a for loop that loops over these elements, and assigns them their respective colour in the colours array by utilising .style.color:

var colours = ['red', 'blue', 'green'];
var elements = document.getElementsByTagName('div');
for (var i = 0; i < elements.length; i++) {
  elements[i].style.color = colours[i]
}
<div>Make me red!</div>
<div>Make me blue!</div>
<div>Make me green!</div>

Hope this helps! :)

RobG
  • 142,382
  • 31
  • 172
  • 209
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
0

you can keep an array of colors you want and then use an index inside replace function to select a color for your replace.

var arr = ['yellow', 'red', 'green'];
var colorIndex = 0;
document.body.innerHTML= document.body.innerHTML.replace(/First Phrase/g, function(m){
   colorIndex %= arr.length;
   return '<span style="background-color:' + arr[colorIndex++] + '">'+m+'</span>';
});
<div>
First Phrase
First Phrase
First Phrase
<div>
Dij
  • 9,761
  • 4
  • 18
  • 35
-1

My advice would be use a jQuery library like the following.

$('body').text().highlight('my text to highlight');
Lime
  • 13,400
  • 11
  • 56
  • 88