Highlight a word with jQuery
Instantly highlight a specific word within text using jQuery by swapping the word with <span class="highlight">word</span>
. Style the .highlight
class in your CSS to make it stand out. Here's the code snippet:
CSS:
Don't forget the \b
delimiters around your word to target whole words only.
Understanding jQuery Highlight
jQuery's interaction with HTML to wrap items and dynamically apply styles possesses some key characteristics:
- Whole word matching:
\b
in RegExp/\bword\b/g
ensures complete words only. Prevents you from falling into the 'therapist' trap (figure it out!). - Casing: It's case-sensitive. 'Word' and 'word' are as different as cats and dogs! For case-insensitive option use
RegExp
with the 'i' flag, like/(\bword\b)/gi
. - Personal touch: Element tags and class names can take on any guise that you desire. Like switching from Clark Kent (
span
) to Superman (div
), or an outfit change ('.highlight' > '.emphasis')!
Multi-word Highlighting, Because Sometimes One is Not Enough
Need to highlight a sentence or a phrase? We've got you covered:
This would highlight the same sequence in the text preserving the pristine nature of the phrase.
Cautious You Must Be, Code Jedi
Be aware that some jQuery plugins, including highlight plugins, may bear hidden scripts. Always fetch your plugins from trusted Jedi councils (repositories) and scrutinize their license and activities. Ensure it's an open-source license, like MIT, so that fellow Jedi can ensure its safety and improve its prowess.
Highlight's Over, Back to Normal
Post-highlight, you may wish to return to normalcy. Here is code to remove highlights:
This function dutifully goes through span.highlight
elements, replacing them with their original text, essentially erasing the highlight.
Party Time! Illuminate That Word!
Here's a more graphical portrayal of highlighting a word using jQuery:
Before we start: "The quick brown fox jumps over the lazy dog."
Set the spotlight (🔦):
And voila!
"The quick brown 🔦fox🔦 jumps over the lazy dog."
Our 'fox' now stands out, shown in all its glory!
Advanced Scenarios: The Next Frontier
Handling Dynamic Content: In with the New
With dynamically generated content, time your call to the highlighting function to occur after the content loads or updates. You may use $(document).ajaxComplete()
enable highlighting post-Ajax calls.
Search As You Go: Lights, Camera, Action!
Create an interactive search that highlights words as users type into the search field. Bind the highlighting function to the keyup
event for a Hollywood-style instant text search.
Preprocessing Text: Makeover Time!
Some text may need a little grooming before the spotlight—normalize case sensitivity or strip diacritics to maintain consistency in search and prevent oddities in highlighting.
Was this article helpful?