[英]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.我正在搜索 web 页面,其中包含来自数组的关键字的产品列表。 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.现在,当它找到关键字时,我希望它使该产品的所有文本(在<div>
标记内)具有浅灰色,以便在向下扫描页面时可以轻松忽略该特定产品。 How can I do this?我怎样才能做到这一点? Here's the demo: JSFiddle这是演示: JSFiddle
Here's the HTML:这是 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:这是 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.您可以检查每个元素的文本并设置其 CSS 颜色属性(如果它与正则表达式匹配)。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.