Search code examples
javascriptjqueryhighlighting

text highlighting using javascript


I am trying to use a text highlight option using javascript.I know how to find the start postiion of the string, bt how do I make it highlight. my code looks like

<div id="entity">health insurance</div>
<div id="article">This kind of insurance is meant to supplement health insurance for cancer-care costs. But generally you're better off putting your money toward comprehensive health policies. </div>

and the javascript that I have used it

$(document).ready(function()
{
var test=document.getElementById('article').innerHTML;
var variable=document.getElementById('entity').innerHTML;
alert(test.search(new RegExp(variable, "i")));
});

This will alert the start postion of the string.


Solution

  • HTML:

    <div id="entity">health insurance</div>
    <div id="article">This kind of insurance is meant to supplement health insurance for cancer-care costs. But generally you're better off putting your money toward comprehensive health policies. </div>​
    

    CSS:

    .highlight {
      background-color: yellow
    }
    

    Javascript:

    $(document).ready(function () {​
      var $test = $('#article');
      var entityText = $('#entity').html();
      var highlight = '<span class="highlight">' + entityText + '</span>';
      $test.html($test.html().replace(entityText, highlight));
    }
    

    Demo: http://jsfiddle.net/ehzPQ/2/

    So, I'm just replacing the first occurrence of the 'entity' string with the same string wrapped up in a span class.

    Did I understood your problem right?

    -----------------------UPDATE-------------------------

    If you want to highlight all the occurrences modify use a regular expression:

    Updated Javascript:

    $(document).ready(function () {
      var $test = $('#article');
      var entityText = $('#entity').html();
      var entityRegularExpression = new RegExp("\\b" + entityText + "\\b", "gi");
      var highlight = '<span class="highlight">' + entityText + '</span>';
      $test.html($test.html().replace(entityRegularExpression, highlight))
    }
    

    And updated demo: http://jsfiddle.net/ehzPQ/3/