jquery - text highlighting using javascript -


i trying use text highlight option using javascript.i know how find start postiion of string, bt how make highlight. code looks like

<div id="entity">health insurance</div> <div id="article">this kind of insurance meant supplement health insurance cancer-care costs. you're better off putting money toward comprehensive health policies. </div> 

and javascript have used

$(document).ready(function() { var test=document.getelementbyid('article').innerhtml; var variable=document.getelementbyid('entity').innerhtml; alert(test.search(new regexp(variable, "i"))); }); 

this alert start postion of string.

html:

<div id="entity">health insurance</div> <div id="article">this kind of insurance meant supplement health insurance cancer-care costs. you're better off putting 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 replacing first occurrence of 'entity' string same string wrapped in span class.

did understood problem right?

-----------------------update-------------------------

if want highlight occurrences modify use 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/


Comments

Popular posts from this blog

jquery - Invalid Assignment Left-Hand Side -

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -