Tutorial: Simple Search Filter with Vanilla JavaScript

<p>Allowing users to filter a large list of items on a website in realtime without reloading the page is one of those things that seems harder than it is, but once you know how it works, it&rsquo;s actually quite simple, and it&rsquo;s an excellent feature to have in your front-end developer tool belt since it never fails to impress users and clients when done well. Let&rsquo;s set up a quick example and walk through the basic pieces.</p> <h1>The HTML</h1> <p>While this example could be extended to work on just about any collection of HTML elements, and filter by any criteria that can be accessed with JavaScript, for the sake of simplicity I&rsquo;ll stick with a single&nbsp;<code>input</code>&nbsp;element with type set to&nbsp;<code>search</code>&nbsp;(we could also use&nbsp;<code>text</code>&nbsp;but the&nbsp;<code>search</code>&nbsp;type gives the user a nice little &ldquo;x&rdquo; they can click to clear out the search term), and an unordered list. The basic HTML looks like this:</p> <pre> &lt;input type=&quot;search&quot;&gt; &lt;ul&gt; &lt;li&gt;Dog&lt;/li&gt; &lt;li&gt;Cat&lt;/li&gt; &lt;li&gt;Hamster&lt;/li&gt; &lt;li&gt;Fish&lt;/li&gt; &lt;li&gt;Chicken&lt;/li&gt; &lt;li&gt;Pig&lt;/li&gt; &lt;li&gt;Cow&lt;/li&gt; &lt;li&gt;Giraffe&lt;/li&gt; &lt;li&gt;Elephant&lt;/li&gt; &lt;li&gt;Tiger&lt;/li&gt; &lt;/ul&gt;</pre> <p>Let&rsquo;s also add an ID to the list to make it easier to target with our JavaScript. That way if there are multiple unordered lists on the page, we&rsquo;ll know we&rsquo;re still targeting the right one. Let&rsquo;s also add a&nbsp;<code>placeholder</code>&nbsp;attribute to the&nbsp;<code>input</code>&nbsp;so the user knows what it&rsquo;s for. The HTML now looks like this:</p> <pre> &lt;input type=&quot;search&quot; placeholder=&quot;Type here to filter the list&quot;&gt; &lt;ul id=&quot;list&quot;&gt; &lt;li&gt;Dog&lt;/li&gt; &lt;li&gt;Cat&lt;/li&gt; &lt;li&gt;Hamster&lt;/li&gt; &lt;li&gt;Fish&lt;/li&gt; &lt;li&gt;Chicken&lt;/li&gt; &lt;li&gt;Pig&lt;/li&gt; &lt;li&gt;Cow&lt;/li&gt; &lt;li&gt;Giraffe&lt;/li&gt; &lt;li&gt;Elephant&lt;/li&gt; &lt;li&gt;Tiger&lt;/li&gt; &lt;/ul&gt;</pre> <p>There&rsquo;s one more piece we&rsquo;ll need to add to get our HTML talking to our JavaScript, but for now we&rsquo;re done.</p> <p><a href="https://medium.com/@cgustin/tutorial-simple-search-filter-with-vanilla-javascript-fdd15b7640bf">Website</a></p>