0

Possible Duplicate:
Highlight a word with jQuery

I want to highlight certain words in html <body> tag, but I want to avoid highlighting those which are within <a> tag. How can this be done? By highlight I mean, underlining and making word bold.

For e.g I have this html content

<body>
<p>
This is sample text for the purpose of highlighting searched text. Please visit <a href="javascript:void(0)">www.sampleSite.com</a>
</p>
</body> 

Now when I search for the word "sample", I would not want to highlight the word sample contained within that anchor tag.

Community
  • 1
  • 1
Shades88
  • 7,934
  • 22
  • 88
  • 130

1 Answers1

2

1. jQuery plugin to do highlighting:

/**
* jQuery plugin to replace text strings
*
* Taken from @link http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/
*/

$.fn.replaceText = function( search, replace, text_only ) {
return this.each(function(){
        var node = this.firstChild,
        val, new_val, remove = [];
        if ( node ) {
            do {
              if ( node.nodeType === 3 ) {
                val = node.nodeValue;
                new_val = val.replace( search, replace );
                if ( new_val !== val ) {
                  if ( !text_only && /</.test( new_val ) ) {
                    $(node).before( new_val );
                    remove.push( node );
                  } else {
                    node.nodeValue = new_val;
                  }
                }
              }
            } while ( node = node.nextSibling );
        }
        remove.length && $(remove).remove();
    });
};

2. CSS to style a span element with a single highlight class

span.highlight{
    font-weight: bold;
    text-decoration: underline;
}

3. jQuery code to run after you have included the plugin & style:

// replace partial string occurrences with a span css styled element
// i.e. textsample => text<span class="highlight">sample</span>
$('p').replaceText(/(sample)/gi, '<span class="highlight">$1</span>');

OR as suggested by @Nick C. in the comments

// replace full string occurrences with a span css styled element
// i.e. ONLY sample => <span class="highlight">sample</span>
$('p').replaceText(/\b(sample)\b/gi, '<span class="highlight">$1</span>');

Here is a demo

The plugin is smart enough not to replace the element's attributes, or text inside elements such as a element...

Community
  • 1
  • 1
Shef
  • 44,808
  • 15
  • 79
  • 90
  • I recommend using word boundaries (\b) to match words. For example, $("p").replaceText(/\b(rain)\b/gi, ...) will match "rain", but not "train". – Nick Clark Aug 21 '11 at 13:28
  • @Nick C.: Well, that's up to the OP if partial occurrences should be highlighted or not. Nonetheless, I will add it in there. Thanks for the comment. – Shef Aug 21 '11 at 13:31
  • 1
    I had to make changes to make it powerful enough to do what I wanted. See: http://stackoverflow.com/a/15212744/470749 – Ryan Mar 04 '13 at 22:55