highlight static html

by Kim Aragon Escobar

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

JavaScript

$('#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)
    })

  }
});