简体   繁体   中英

How to search for keywords from array and highlight all text in parent div tag using JavaScript

I'm searching a web page containing a list of products for keywords from an array. When it finds any word in the array it highlights it with a red background. That works fine. Now, when it finds the keywords I want it to make all of the text for that product (within the <div> tag) to have a light grey colour so I can easily ignore that particular product when scanning down the page. How can I do this? Here's the demo: JSFiddle

Here's the HTML:

<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>

Here's the JavaScript:

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

You can check the text of each element and set its CSS color property if it matches the regular expression.

 var regex = /(apples|oranges)/g; $('body a, body p, body div').each(function() { var $this = $(this); var text = $this.text(); if (text.match(regex)) { $this.css("color", "grey"); if($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> <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM