PapelPincel
PapelPincel

Reputation: 4393

: How to highlight certain words with jQuery

I'm looking for a script than can highlight a certain number of words depending on their position. example, for the following contentI want to highlight only the second, third and fourth words:

<p>
    Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero.
    Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>

the result should be like :

<p>
    Quisque <span class="highlight">bibendum sem ut</span> lacus. Integer dolor ullamcorper libero.
    Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>

Thank you very much !

Upvotes: 1

Views: 5832

Answers (2)

Hawkee
Hawkee

Reputation: 2027

I wrote a very simple function that uses jQuery to iterate the elements wrapping each keyword with a .highlight class.

function highlight_words(word, element) {
    if(word) {
        var textNodes;
        word = word.replace(/\W/g, '');
        var str = word.split(" ");
        $(str).each(function() {
            var term = this;
            var textNodes = $(element).contents().filter(function() { return this.nodeType === 3 });
            textNodes.each(function() {
              var content = $(this).text();
              var regex = new RegExp(term, "gi");
              content = content.replace(regex, '<span class="highlight">' + term + '</span>');
              $(this).replaceWith(content);
            });
        });
    }
}

More info:

http://www.hawkee.com/snippet/9854/

Upvotes: 1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 828050

This jQuery plugin is what you're looking for:

It does exactly what you want, traverses the DOM TextNodes and looks for the text to search, when it find one occurrence it creates an span element.

Usage :

$('p').highlight('bibendum sem ut'); 

Upvotes: 4

Related Questions