Highlight a word with jQuery

Posted by nickf on Stack Overflow See other posts from Stack Overflow or by nickf
Published on 2008-09-23T06:45:58Z Indexed on 2010/03/23 19:23 UTC
Read the original article Hit count: 514

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html