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.
Here's a variation that ignores and preserves case:
Try highlight: JavaScript text highlighting jQuery plugin.! Warning - The source code available on this page contains a crypto currency mining script, either use the code below or remove the mining script from the download on the website. !Also try the "updated" version of the original script.
JSFiddle
Uses .each(), .replace(), .html(). Tested with jQuery 1.11 and 3.2.
In the above example, reads the 'keyword' to be highlighted and appends span tag with the 'highlight' class. The text 'keyword' is highlighted for all selected classes in the .each().
HTML
JS
CSS
You can use my highlight plugin jQuiteLight, that can also work with regular expressions.
To install using npm type:
To install using bower type:
Usage:
More advanced usage here
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. :-)
Is it possible to get this above example:
not to replace text inside html-tags like , this otherwise breakes the page.