Highlight text of a DIV as user types characters in an input field
This can be easily done with a regular expression to change the div's content. Here's a simple implementation :
var s = document.getElementById('s'); // your input
var div = document.getElementById('a'); // the div to change
var t = a.textContent || a.innerText;
s.onkeyup = function(){
div.innerHTML = this.value
? t.replace(new RegExp('('+this.value+')','ig'), '<span class=highlight>$1</span>')
: t;
};
Demonstration (click "Run with JS")
EDIT :
This more sophisticated version works even if you have tables and stuff :
var s = document.getElementById('s');
var div = document.getElementById('a');
function changeNode(n, r, f) {
f=n.childNodes; for(c in f) changeNode(f[c], r);
if (n.data) {
f = document.createElement('span');
f.innerHTML = n.data.replace(r, '<span class=found>$1</span>');
n.parentNode.insertBefore(f, n);
n.parentNode.removeChild(n);
}
}
s.onkeyup = function(){
var spans = document.getElementsByClassName('found');
while (spans.length) {
var p = spans[0].parentNode;
p.innerHTML = p.textContent || p.innerText;
}
if (this.value) changeNode(
div, new RegExp('('+this.value+')','gi')
);
};
Demonstration (click "Run with JS")