Better "find and highlight" implementation in HTML element I'm trying to figure out what is best and fastest implementation of a browser-like find and highlight function inside a website using JavaScript.
This function is for one HTML element without any children. Of course it can be expanded to elements with children with some simple loops. That is not part of question.
I wrote this small code to make something working here:

CSS

span.highlight{background:yellow; padding:3px;}


HTML

&lt;input type="search"/&gt;
&lt;p&gt;The Ama...&lt;/p&gt;


JavaScript

var s = document.querySelector('input[type="search"]'),
    p = document.querySelector('p'),
    find = function(){
    var words = p.innerText.split(' ');
    for(var i=0; i&lt;words.length; i++){
        if(words[i].toLowerCase() == s.value.toLowerCase()){
            words[i] = '&lt;span class="highlight"&gt;' + words[i] + "&lt;/span&gt;";
            p.innerHTML = words.join(' ');
        }
        else{

        }   
    }
}
s.addEventListener('keydown', find , false);
s.addEventListener('keyup', find , false);


This code is working fine. Checkout live example here. But this is not fast and sometimes crash the browser. How can I make this functionality with a better approach?

Please note I don't want a full code review here. So don't remind me that querySelector is not supported in IE7 and same things.
Let's start by optimising your code.  Simply said, loops are the danger here.


A while loop can be quicker than a for loop, especially in cases like this. Get the length once.
Avoid looking into arrays.  Do word = words[i] once, which is much faster.
You are joining in every iteration. You should join once only after you have updated your array.
I guess the empty else isn't done yet.




var s = document.querySelector('input[type="search"]'),
    p = document.querySelector('p'),
    find = function(){
        var words = p.innerText.split(' '),
            i = words.length,
            word = '';

        while(--i) {
            word = words[i];
            if(word.toLowerCase() == s.value.toLowerCase()){
                words[i] = '&lt;span class="highlight"&gt;' + word + "&lt;/span&gt;";
            }
            else{

            }   
        }

        p.innerHTML = words.join(' ');
    }

s.addEventListener('keydown', find , false);
s.addEventListener('keyup', find , false);


Last but surely not least, the page you want to read.