开发者

How to highlight words in html using jquery [duplicate]

This question already has answers here: Closed 11 years ago.

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="jav开发者_如何学编程ascript: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.


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜