Reputation: 105
I have some old code that I use to hightlight a list of words:
jQuery.fn.highlight = function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(pat);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
}
else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.length && pat && pat.length ? this.each(function() {
innerHighlight(this, pat.toUpperCase());
}) : this;
};
$(document).ready(function(){
$("td").highlight("car")
$("td").highlight("sales");
$("td").highlight("income");
});
</script>;
Very similar to this post: Search and Highlight in jQuery
But now I need the same script to highlight a 2nd list with a different color on the same page. What I am asking for is very similar to this post: Using multiple colors for highlighting
Can't seem to get it.
Upvotes: 0
Views: 70
Reputation: 1332
(Updated answer based on OP's feedback...)
The quickest solution for you is to modify your existing function so that it accepts a 2nd argument specifying which CSS className to add to the highlight span.
(Or more specifically in my example below, not the entire CSS className, but just the color portion. This is appended to the stem "highlight-" automatically to save you having to type the whole thing every time you call the function.)
So...
// 1. Change: jQuery.fn.highlight = function(pat) {
// to...
jQuery.fn.highlight = function(pat, color) {
// 2. Change: spannode.className = 'highlight';
// to...
spannode.className = 'highlight-'+color;
Your function now accepts a 2nd argument called 'color' and spannode.className
is dynamic according to the color specified.
// 3. Add some classes like these to your CSS...
//
.highlight-red {background-color:red;}
.highlight-green {background-color:green;}
.highlight-pink {color:white;font-weight:bold; background-color:pink;}
// 4. Then call your function like this...
//
$("td").highlight("car", 'red')
$("td").highlight("sales", 'green');
$("td").highlight("income", 'pink');
Upvotes: 0