highlight text
by slawe
HTML
<input id=s>
<div id=a>
I have seen many posts pertaining to highlighting text in a DIV using javascript, but none do quite what I'm looking for.
What I need to do is highlight the text within a specific DIV, character by character as the user enters the search term. Conversely, as the user backspaces or deletes characters, I need to "de-highlight" the text of the same DIV.
I imagine this has already been done somewhere by someone, but I have not yet found a post here or from Google that behaves exactly as I need.
Any feedback is appreciated.
<!-- <table border=2><tr><td>in table</td><td>it works n the table!</td></tr></table> -->
</div>
CSS
.highlight {
color: #ff0000;
}
JavaScript
var s = document.getElementById('s');
var div = document.getElementById('a');
var t = a.textContent || a.innerText;
s.onkeyup = function(){
div.innerHTML = this.value ? t.replace(new RegExp('('+this.value+')','gi'), '<span class="highlight">$1</span>') : t;
};
/*
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="highlight">$1</span>');
n.parentNode.insertBefore(f, n);
n.parentNode.removeChild(n);
}
}
s.onkeyup = function(){
var spans = document.getElementsByClassName('highlight');
while (spans.length) {
var p = spans[0].parentNode;
p.innerHTML = p.textContent || p.innerText;
}
if (this.value) changeNode(
div, new RegExp('('+this.value+')','gi')
);
};
*/