I am currently looking for a webpage that displays a list of products based on keywords from an array. Once it detects any word in the array, it highlights it with a red background - everything is working smoothly so far. However, I now wish for the script to change the color of the entire product text (within the <div>
tag) to light grey, allowing me to easily skip past that specific product when scanning through the page. Is there a way to achieve this? You can view the demo here: JSFiddle
This is the HTML code:
<div>
<p>I bought some apples.</p>
<p>Apples are £2 per kg.</p>
</div>
<hr>
<div>
<p><a href="oranges.html">I bought some oranges.</a></p>
<p>Oranges are £1.50 per kg.</p>
</div>
<hr>
<div>
<p><a href="pears.html">I bought some pears.</a></p>
<p>Pears are £1.80 per kg.</p>
</div>
And this is the JavaScript code:
var regex = /(apples|oranges)/g;
$('body a, body p').each(function() {
var $this = $(this);
var text = $this.text();
if (text.match(regex) && $this.children().length===0) {
$this.html(
$this.html().replace(regex, '<span style="background: #fa7373;">$1</span>')
);
}
});