Reputation: 1254
The code below is based on the samples provided in this example: StackOverflow Question
I am no good with JS but would like to adjust this code to highlight not just a number located in a on the website, but rather highlight specific text located anywhere in the active tab, by either changing the font color or the highlighting the text. How can I do that?
Appreciate any help, I am new to JS and a little lost. Thanks, A2k
EDIT: To clarify, I want to highlight the words Apple, Banana, etc. when they are located ANYWHERE in the active tab, not necessarily in a table or a td. This means the words can just as well be in a paragraph of text, in a label, an input field, etc.
highlightText.js
// keyword to highlight
var keywordArray = ["apple","banana","orange"];
keywordArray.forEach(function(v){
var num = "(" + v + ")";
// Select the '<td>' that contains the number we are looking for
var td = $('td.col-question:contains('+num+')');
// Make sure that this number exists
if(td.length > 0){
// Now that we have it we need to single out the number and replace it
var span = td.html().replace(num,'<span class="highlight-num">'+num+'</span>');
var n = td.html(span);
}
// Now instead of '(1000)' we have
// '<span class="highlight-num">(1000)</span>'
// We will color it in the css file
});
highlight.css
span.highlight-num{
background-color: rgb(100, 255, 71);
}
Upvotes: 0
Views: 239
Reputation: 50684
Your issue is with:
var num = "(" + v + ")";
By doing this you are checking if the fruit (apple)
, (banana)
or (orange)
is in your table. Instead, you can remove this to check whether apple
, banana
or orange
is contained in your table.
You can instead use a regular expression to replace the keywords if they appear with spans around them to highlight them.
This does have its downsides however, as it won't work properly with text inputs as the markup will not be rendered as HTML.
See working example below:
$(function() {
const keywordArray = ["apple", "banana", "orange"];
const body = $('body');
body.html((_, innerHTML) =>
innerHTML.replace(new RegExp(`(${keywordArray.join('|')})`, 'g'), '<span class="highlight-num">$1</span>')
);
});
span.highlight-num {
background-color: rgb(100, 255, 71);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<p>The big apple is big</p>
<em>The orange <strong>orange</strong> is orange</em>
<br />
<span>The green grape is green</span>
<h4>The banana is a banana</h4>
</body>
Upvotes: 2