Question

I am using the method below to search for a string in a web page. It matches plain text; but, it fails in the following context:

 <span>I</span> am searching for <b>text</b>

If I search for "am searching" it will match.. But if I search for "I am searching" it does not match. Below is the code I am using:

function search(text)
{
    if (document.body.createTextRange) 
    {
        var textRange = document.body.createTextRange();
        while (textRange.findText(text)) 
        {
            textRange.execCommand("BackColor", false, "yellow");
            textRange.collapse(false);
        }
    }
}

here is the fiddle. It is not working in IE8. Thanks

Was it helpful?

Solution

<script type="text/javascript">
function findText(text) {
    $('*:contains('+text+')').css('background-color', 'Yellow');
});
</script>

<script type="text/javascript">
function findText(textBoxOrHtmlTagId, text) {
    $('#'+textBoxOrHtmlTagId+':contains('+text+')').css('background-color', 'Yellow');
});
$(document).ready(function(){
    $('#yourid').live('keydown', findText('yourid', $('#yourid').text());
});
</script>

Should work: in short use jquery

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top