Todd Williams Todd Williams - 1 year ago 92
jQuery Question

How to highlight a word in another element using Regex and anchor tags

I want to be able to click on the anchor tag and have it highlight the corresponding word in the div below it. It seems like every example I've seen to do this requires an input, but I'd like to be able to do it with a button or anchor tag. Here is my fiddle that's not working yet. Is there something I'm missing?

$('#search').click(function () {
var test = new RegExp(
$('#search').text().replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'),
$('#sample').children().addBack().not('.highlight').contents().filter(function() {
return this.nodeType === 3;
return this.str.replace(test, '<span class="highlight">$&</span>');


Answer Source

To be honest, I couldn't understand your code very well. but I've coded something that works for what you need, i.e:

When #search is clicked we retrieve its text() and replace #sample with <span class="highlight">text of #search</span>.
When #revert is clicked we replace #sample html() with #sample text() only.

$('#search').click(function () {
    var re = new RegExp("\\b" + $("#search").text() + "\\b","ig");
    $("#sample").html($("#sample").text().replace(re, '<span class="highlight">$&</span>'))

.highlight {
<script src=""></script>
<a href="#" id="search">Yoda</a>
<button id="revert">Revert!</button>
<p id="sample">Highlight the word Yoda Yodada</p>


  1. The regex has word boundaries (\b) and will match Yoda but not Yodada
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download