2

I am a bit new to JavaScript, and just want to search my website for a particular string of text and find it, list it or whatever.

I looked at this solution: Javascript Search Engine (Search own site)

But am not getting what I want out of it. I'm sure my syntax from HTML to JavaScript is a bit off. I am happy to search the current page for now, but will ultimately want to span across all HTML pages, which are all in a single directory.

Here is my code, and it does not error, but it also does not appear to do anything except clear the textbox.

I have gone through a plethora of examples using W3Schools and some other textbooks on Safari

<!DOCTYPE HTML>
    <head>
        <style>

        </style>

    </head>

    <body>
        <br>
        <input type="number" id="str">
        <button onclick="findInPage(str.value)">Search</button>
        <script language=JavaScript>
            var NS4 = (document.layers);    
            var IE4 = (document.all);
            var win = window;    
            var n = 0;
            function findInPage(str) {
                var txt, i, found;
                if (str == "") 
                    return false;

                if (NS4) {
                    if (!win.find(str))
                        while(win.find(str, false, true))
                            n++;
                    else
                        n++;

                    if (n == 0)
                        alert("Not found.");

                    }

                if (IE4) {
                    txt = win.document.body.createTextRange();
                    for (i = 0; i <= n && (found = txt.findText(str)) != false; i++) {
                        txt.moveStart("character", 1);
                        txt.moveEnd("textedit");

                    }

                if (found) {
                    txt.moveStart("character", -1);
                    txt.findText(str);
                    txt.select();
                    txt.scrollIntoView();
                    n++;

                }

                else {
                    if (n > 0) {
                    n = 0;
                    findInPage(str);

                    }

                    else
                        alert("Sorry, we couldn't find. Try again");

                    }

                }
                return false;

            }

        </script>

    </body>

</HTML>
ssabc
  • 21
  • 1
  • TextRange is for editing rich texts like Word does. What you are trying to do is more achievable using xpath and css selectors. Check this out: https://developer.mozilla.org/en-US/docs/Web/XPath and this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_using_XPath_in_JavaScript – Marco Apr 24 '19 at 17:56

0 Answers0