Highlighting Search Keywords in a HTML DIV Control Using Javascript

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!!!!!!!!!! πŸ™‚

4 Responses to Highlighting Search Keywords in a HTML DIV Control Using Javascript

  1. Fazeel says:

    Can you show me the sample demo or example here..??

    • panchalvimal says:

      Hi Fazeel,

      Right now i do not have any example for this. That’s why i already provide the function code, which you just copy to page and use it directly.

      I also explained about what are the parameters you have to pass to this function.

      Still, if you have any query ask me.

      Regards,
      Vimal

Leave a comment