Highlighting Search Keywords in a HTML DIV Control Using Javascript

March 15, 2010

In many of the popular search engines (most of all ones), when you perform a search the resulting page displays the word(s) you searched on are highlighted different colors to make them easy to pick out.
This article will examine how to provide such functionality in HTML DIV control with the use of a simple javascript function.
Lets Start…….. 🙂

Here is the Javascript function will do that.

objDIV = Div which contains the Text Contents
textToHightLight = Text (Searched Word) which should be Highlighted

function innerHighlight(objDIV, textToHightLight)
{
var skip = 0;
if (objDIV.nodeType == 3)
{
var pos = objDIV.data.toUpperCase().indexOf(textToHightLight.toUpperCase());
if (pos >= 0)
{
var spannode = document.createElement(‘span’);
spannode.className = ‘highlight’;
var middlebit = objDIV.splitText(pos);
var endbit = middlebit.splitText(textToHightLight.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
}
else if (objDIV.nodeType == 1 && objDIV.childNodes && !/(script|style)/i.test(objDIV.tagName))
{
for (var i = 0; i < objDIV.childNodes.length; ++i)
{
i += innerHighlight(objDIV.childNodes[i], textToHightLight);
}
}
return skip;
}

In the code note that i have set the className for the SPAN Element to 'highlight'. This HTML will apply the style of a particular class to the word we wish to highlight. Feel free to use whatever CSS markup you'd like to in order to have the search word "highlighted." The below CSS will give the highlighted word a yellow background.

.highlight {text-decoration: none;color:black;background:yellow;}

Happy codding!!!!!!!!!! 🙂