3

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

Exception
  • 8,111
  • 22
  • 85
  • 136
  • 2
    Your fiddle selects "formatting" just fine for me in IE9, even if I emulate IE7. It only does not seem to work on IE8. – pimvdb Nov 27 '11 at 10:06
  • This seems bugged in IE8. I can't even think of a workaround because you can't create your own textrange object. Oddly the textRange.text value is correct in that it doesn't include the tags, but findText is broken it seems. You may be out of luck here as I doubt MS is going to fix anything in IE8 at this point. – mrtsherman Nov 27 '11 at 10:27
  • 1
    Any specific reason it's not meant to work in real browsers? – Stein G. Strindhaug Nov 27 '11 at 10:37
  • 1
    There is a workaround posted here : http://stackoverflow.com/questions/130186/ie-textrange-select-method-not-working-properly – Zakaria Nov 27 '11 at 10:58

1 Answers1

1
<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