So, I think the solution to your problem is that you only need to get the contents of the anchors you want to highlight. Here follows jsfiddle: https://jsfiddle.net/kimaescobar/k83j7Lqv/1/ but basically I created a class in searchable anchors, than I get all searchable ones that are inside the all_text object:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script> <input type="text" id="searchfor" /> <ul id="all_text"> <li><a class="searchable" href="/somewhere">Somewhere</a></li> <li><a class="searchable" href="/somewhere-else">Over there</a></li> </ul>
CSS
#all_text em { text-decoration: underline; background-color: yellow; }
Js
$('#searchfor').keyup(function(){ var $page = $('#all_text .searchable'); $page.each(function(i,a){ $a = $(a) $a.html($a.html().replace(/<em>/g,"").replace(/\<\/em\>/g,"")) }) var searchedText = $('#searchfor').val(); if(searchedText != ""){ $page.each(function(i,a){ $a = $(a) var html = $a.text().replace(new RegExp("("+searchedText+")", "igm"), "<em>$1</em>") $a.html(html) }) } });
obs: I changed from span to em, because semantically in html5, when you want to highlight something that you use strong or em (depending on the selected semantics).
source share