Search code examples
javascripthtmlwordsearch

Word search with span element count


I'm working on making a word search for whatever word is entered into the input box. I'm trying to create a div element that would show a string consisting of all words found at least once in each paragraph, for successive searches, below the input box. I also want to create a span element that maintains a count of the words that are found in all paragraphs for all searches. I'm just pretty lost with all of it and unsure where to even start.

/*window.onload = function()
 {
document.getElementById("searchbutton").onclick = searchClick;

};
  I needed to bring  this one line lower to work on commenting out  */

but1 = document.querySelector("#searchbutton");
but1.addEventListener('click', searchClick);


// Called when the Search button is clicked.
// Looks for paragraphs matching a search string and highlights them. 

function searchClick() {
  var searchPhrase = document.getElementById("searchtext").value;
  /*var main = document.querySelector("#main");*/
  var mainParas = document.getElementsByTagName("p");

  for (var i = 0; i < mainParas.length; i++) {

    if (mainParas[i].textContent.indexOf(searchPhrase) >= 0) { mainParas[i].className = "highlighted"; }    // highlight 
    else {
      mainParas[i].className = null; // un-highlight
    }

  }

}
<body>
  <div id="main">
    <p>The Phoenix Suns are a professional basketball team based in
      Phoenix, Arizona. They are members of the ...</p>
    <p>The Suns have been generally successful since they began play as an
      expansion team in 1968. In forty years of play they have posted ...</p>
    <p>On January 22, 1968, the NBA awarded expansion franchises to an
      ownership group from Phoenix and one from Milwaukee. ...</p>
    <ul>
      <li>Richard L. Bloch, investment broker/real estate developer...</li>
      <li>Karl Eller, outdoor advertising company owner and former...</li>
      <li>Donald Pitt, Tucson-based attorney;</li>
      <li>Don Diamond, Tucson-based real estate investor.</li>
    </ul>
  </div>

  <p>Page by Marty Stepp. <br />
    Some (all) information taken from Wikipedia.</p>
  <hr />

  <div>
    Search for text:
    <input id="searchtext" type="text" />
    <button id="searchbutton">Search</button>
  </div>
</body>


Solution

  • Your problem seems to be that document.querySelector("#searchbutton") returns null so that but1.addEventListener('click', searchClick); fails. Instead of searching for the reason I skipped adding a listener and directly attached the onclick function with

    <button id="searchbutton" onclick="searchClick()">Search</button>
    

    in the html. This worked, but I had to define a css rule for highlighting that wasn't posted in your code.

    Edit 01.05.2021 - I didn't cover counting the matches, so here it is completely:

    <!DOCTYPE html>
    <html>
        <head>
            <title>Test</title>
            <style>
                p.highlighted { background-color: Yellow; }
            </style>
        </head>
        <body>
        <body>
            <script type="text/javascript">
                function searchClick() {
                    var count = 0;
                    var searchPhrase = document.getElementById("searchtext").value;
                    var mainParas = document.getElementsByTagName("p");
                    for (var i = 0; i < mainParas.length; i++) {
                        if (mainParas[i].textContent.indexOf(searchPhrase) >= 0) {
                            mainParas[i].className = "highlighted"; // highlight
                            count += mainParas[i].textContent.split(searchPhrase).length - 1;
                        } else {
                            mainParas[i].className = null; // un-highlight
                        }
                    }
                    document.getElementById("found").textContent = count + " matches found";
                }
            </script>
            <div id="main">
                <p>The Phoenix Suns are a professional basketball team based in Phoenix, Arizona. They are members of the ...</p>
                <p>The Suns have been generally successful since they began play as an expansion team in 1968. In forty years of play they have posted ...</p>
                <p>On January 22, 1968, the NBA awarded expansion franchises to an ownership group from Phoenix and one from Milwaukee. ...</p>
                <ul>
                    <li>Richard L. Bloch, investment broker/real estate developer...</li>
                    <li>Karl Eller, outdoor advertising company owner and former...</li>
                    <li>Donald Pitt, Tucson-based attorney;</li>
                    <li>Don Diamond, Tucson-based real estate investor.</li>
                </ul>
            </div>
            <p>Page by Marty Stepp. <br />
            Some (all) information taken from Wikipedia.</p>
            <hr />
            <div>Search for text:
                <input id="searchtext" type="text" />
                <button id="searchbutton" onclick="searchClick()">Search</button>
                <span id="found"></span>
            </div>
        </body>
    </html>
    

    The counting happens with the loop checking the paragraphs. Before, a variable count is defined, inside it gets increased if matches occur, and after the loop the span id="found" is updated with the value of that variable.

    For counting matches of the phrase and not numbers of paragraphs with matches, the text content is split up using the search phrase as delimiter. Then the number of pieces minus one is the number of occurences. Counted are phrases, not words. The phrase "the" is found in both " the " and " they ", but not in "The". Case sensitivity wasn't asked and isn't hard to implement. Just uppercase both the search phrase and the text being searched.

    For simplicity, I put together HTML, Javascript and CSS into one file.