Search code examples
documentwords

searching for elements


I was assigned homework in which I had to take the given HTML file and create a Javascript file which would search for words within a div class. I have to use both document.getElementById() and .querySelectorAll.


Solution

  • You need to get the elements with: document.querySelectorAll(".main"); and then you need to get the search with document.getElementById("searchtext"), and then you can add use addEventListener to make it run your function when a click event occurs:

    function Search() 
    {
        var elements = document.querySelectorAll(".main");
        let search = document.getElementById('searchtext').value;
        for (var i = 0; i < elements.length; i++)
        {
            if(elements[i].innerHTML.indexOf(search) > - 1)
            {
                alert('found');
            }
        }
    
    }
    
    document.getElementById('searchbutton').addEventListener('click', Search);
        <body>
    
            <div class="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>
    
            <p>Page by New Person. <br /> Some (all) information taken from Wikipedia.</p>
    
            </div>
    
            <hr />
    
            <div>
    
                Search for text:
                <input id="searchtext" type="text"  /> 
                <button id="searchbutton">Search</button>
            </div>
    
        </body>