Todd Williams Todd Williams - 6 months ago 9
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?

http://jsfiddle.net/NVeMD/6/

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

$('#revert').click(function(){
$(".highlight").contents().unwrap();
});

Answer

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>'))
});

$('#revert').click(function(){
    $("#sample").html($("#sample").text());
});
.highlight {
    background-color:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="search">Yoda</a>
<button id="revert">Revert!</button>
<p id="sample">Highlight the word Yoda Yodada</p>


Note:

  1. The regex has word boundaries (\b) and will match Yoda but not Yodada