How to highlight all links containing keywords from array using JavaScript

Viewed 321

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>')
        );
    }
});
2 Answers

Remove </a> from your code. This </a> is closing any anchor tag.

var regex = /(apples|oranges)/g;

$('*').each(function() {
    var $this = $(this);
    var text = $this.text();
    if (regex.test(text)) {
        $this.html(
            $this.html().replace(regex, '<mark>$1</mark>')
        );
    }
});

You should be selecting all p and a tags in the body instead of using * which will even select the script tag itself. Also, remove the </a> that is closing any anchor tag. To not modify the HTML of anchor tags, you can check that the current element has no children before replacing.

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>')
        );
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
I bought some apples.
</p>

<p>
<a href="oranges.html">I bought some oranges.</a>
</p>

<p>
I bought some pears.
</p>

Related