views:

6544

answers:

11

I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word "dolor" in this text:

<p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
</p>
<p>
    Quisque bibendum sem ut lacus. Integer dolor ullamcorper libero.
    Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>

How do I convert the above to something like this:

<p>
    Lorem ipsum <span class="myClass">dolor</span> sit amet, consectetuer adipiscing elit.
</p>
<p>
    Quisque bibendum sem ut lacus. Integer <span class="myClass">dolor</span> ullamcorper
    libero. Aliquam rhoncus eros at augue. Suspendisse vitae mauris.
</p>

Is this possible with jQuery?

Edit: As Sebastian pointed out, this is quite possible without jQuery - but I was hoping there might be a special method of jQuery which would let you do selectors on the text itself. I'm already using jQuery heavily on this site, so keeping everything wrapped up in jQuery would make things perhaps a bit more tidy.

A: 

You need to get the content of the p tag and replace all the dolors in it with the highlighted version.

You don't even need to have jQuery for this. :-)

Sebastian Hoitz
But it's easier with jQuery, isn't it? ;)
Eikern
+17  A: 

Maybe you can use highlight: JavaScript text higlighting jQuery plugin

mlarsen
A: 

If you're really game you could look through the source of StackOverflow for how it does syntax highlighting on the code blocks ;)

Essentially you'll have to just dynamically insert HTML (spans would be best) where you need them.

Slace
A: 

This may also be of interest: http://www.jquery.info/The-plugin-SearchHighlight

Eikern
+1  A: 
function hiliter(word, element) {
    var rgxp = new RegExp(word, 'g');
    var repl = '<span class="myClass">' + word + '</span>';
    element.innerHTML = element.innerHTML.replace(rgxp, repl);
}
hiliter('dolor');
Andrew Hedges
+9  A: 

You could just write your own plugin for jQuery.

Taking basis in Andrew Hedges' example above:

jQuery.fn.highlight = function (str, className)
{
    return this.each(function ()
    {
        this.innerHTML = this.innerHTML.replace(
            new RegExp(str, "g"),
            "<span class=\"" + className + "\">" + str + "</span>"
        );
    });
};

And you would use it like so:

$("selector").highlight("string to highlight", "highlight-class");

This example is much faster than the before-mentioned plugin. Read: http://stackoverflow.com/questions/117665/jquery-fastest-dom-insertion

roosteronacid
It also breaks badly when the target `str` is found within markup (this can even result in HTML-injection vulnerabilities), and in the process of rewriting the element's content it destroys all non-serialisable content, like form field values, JS references and event handlers. Avoid.
bobince
A: 

Is it possible to get this above example:

jQuery.fn.highlight = function (str, className)
{
    var regex = new RegExp(str, "g");

    return this.each(function ()
    {
        this.innerHTML = this.innerHTML.replace(
            regex,
            "<span class=\"" + className + "\">" + str + "</span>"
        );
    });
};

not to replace text inside html-tags like , this otherwise breakes the page.

+2  A: 

Hey, I wrote a plugin that does exactly this -- it's like the Johann Burkard plugin mlarsen posted, but works with regular expressions instead of strings. Check it out on github and please let me know if there are additional features you need.

A: 

To Fredrik Söderstr, poster (and creator?) of that text highlight function,

Thank you. It works perfectly. I use a tooltip ( http://craigsworks.com/projects/simpletip/# ) that looks for the the class that is created. All I do is call this highlight function first which creates the class, then I call my tooltip class which looks for that class.

Now when the word "Original" shows up and the user mouses over it, a tooltip explains what I mean by "original". Perfect.

Thank you very much,

Andrew

Andrew Evans
A: 

Here's a variation that ignores and preserves case:

jQuery.fn.highlight = function (str, className) {
    var regex = new RegExp(str, "gi");

    return this.each(function () {
        this.innerHTML = this.innerHTML.replace(regex, function(matched) {return "<span class=\"" + className + "\">" + matched + "</span>";});
    });
};
bjarlestam
A: 

Instead of Js, you can simply use css to achieve this...

Answer to a smilar question

FallenAngel
The question asks how to highlight a given search term, not change the colour of user-selected text.
nickf