Forum Moderators: open

Message Too Old, No Replies

find text, wrap it in something - how?

for highlighting search text on a page of content

         

httpwebwitch

1:48 am on Apr 4, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I want to parse all the CDATA on a page, match it against a regular expression, then if found wrap matches in a <span>. The implementation is obvious: I want to highlight search text on the page.

For several reasons this has to be a client-side solution, even though doing it server-side would have been easier. :S

Can anyone give me a nudge in the right direction?

coopster

1:23 pm on Apr 4, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



A quick search over the forum turns up a few solutions in regards to Highlighting text with CSS/javascript [webmasterworld.com]

Dabrowski

6:21 pm on Apr 4, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Easy solution, use a JS regular expression:


function highlightText( word) {
var obj = document.getElementsByTagName( "contentToHighlight");
var re = new RegExp( "\\b("+ word +")\\b");

obj.innerText = obj.innerText.replace( re, "<span class='highlighted'>$1</span>");
}

Should do it.