Create a variable to store entered phrase:
var word = '';
Write an event handler
$(document).on('keypress', highlight);
Now implement hightlight function:
function highlight(event) { // ... }
Add pressed key to phrase:
word += String.fromCharCode(event.which);
Extract innerText from all <a> elements, then add hightlights, by wrapping phrase with an <span> element
$('li>a').each(function() { var element = $(this); var text = element.text(); text = text.replace(new RegExp('(' + word + ')', 'ig'), '<span class="highlight">$1</span>'); element.html(text); });
Add a style to .highlight selector:
<style> span.highlight { color: red; } </style>
By combining all code, it should be like below:
var word = ''; function highlight(event) { word += String.fromCharCode(event.which); $('li>a').each(function() { var element = $(this); var text = element.text(); text = text.replace(new RegExp('(' + word + ')', 'ig'), '<span class="highlight">$1</span>'); element.html(text); }); } $(document).on('keypress', 'highlight');
There is still one problem left, when would be the phrase be cleared, after a certain time that document doesn't receive any keypress event, or is there any other strategy?