I'm searching a web page for keywords from an array. This code works by replacing text with a tag which highlights the text, but when it finds keywords that are links then it breaks them because it puts a <span> tag within the <a> tag.
I tried to refer to the parent element by changing $this.html() to $this.parent.html() but this didn't work. Here's the JSFiddle: https://jsfiddle.net/uzfsjqyr/1/
I'd appreciate some help, please?
var regex = /(Apples|oranges)/g;
$('*').each(function() {
var $this = $(this);
var text = $this.text();
if (regex.test(text)) {
$this.html(
$this.html().replace(regex, '</a><span style="background: #fa7373;">$1</span>')
);
}
});