Forum Moderators: open

Message Too Old, No Replies

Replicating the Google Highlight

highlight search terms, javascript span highlight

         

numbchuckskills

3:13 pm on Aug 11, 2006 (gmt 0)

10+ Year Member



Hey all,

Im working on a tool that needs some highlighting for a specified search term...i've pasted the source code below for my highlight method. I'm running into a problem when the search term is found in a link such as the following case:

1. Search for "Widget 1"
2. A link is found with [customersite.com...] 1 Files/1.ppt
3. My method wraps a yellow span around "Widget 1" making the link useless.

Is there any way to ignore the <a> tag when doing the text replace? This is the code:

function highlight()
{
if(document.getElementById('txtSearchAll').value!="")
{
var term = document.getElementById('txtSearchAll').value;

toUpper();
var text = document.getElementById("results").innerHTML;
var termlow = term.toLowerCase();
var termhigh = term.toUpperCase();

var strReplaceAll = text;
text = text.toString();

var regExnormal = "/"+term+"/g";
var regExlower = "/"+termlow+"/g";
var regExupper = "/"+termhigh+"/g";

text = text.replace(eval(regExnormal), "<span style=\"background-color:#FFFF00;\">"+term+"</span>" );
text = text.replace(eval(regExlower), "<span style=\"background-color:#FFFF00;\">"+term+"</span>" );
text = text.replace(eval(regExupper), "<span style=\"background-color:#FFFF00;\">"+term+"</span>" );
document.getElementById("results").innerHTML = text;

}
}
}

Thanks!

Fotiman

4:53 pm on Aug 11, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



This is only a guess, but I think what you'll want to do instead is walk through the DOM, inspecting only the nodes of type TEXT_NODE and which don't have a parent node of ATTRIBUTE_NODE.