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’s actually quite simple, and it’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’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’ll stick with a single <code>input</code> element with type set to <code>search</code> (we could also use <code>text</code> but the <code>search</code> type gives the user a nice little “x” they can click to clear out the search term), and an unordered list. The basic HTML looks like this:</p>
<pre>
<input type="search">
<ul>
<li>Dog</li>
<li>Cat</li>
<li>Hamster</li>
<li>Fish</li>
<li>Chicken</li>
<li>Pig</li>
<li>Cow</li>
<li>Giraffe</li>
<li>Elephant</li>
<li>Tiger</li>
</ul></pre>
<p>Let’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’ll know we’re still targeting the right one. Let’s also add a <code>placeholder</code> attribute to the <code>input</code> so the user knows what it’s for. The HTML now looks like this:</p>
<pre>
<input type="search" placeholder="Type here to filter the list">
<ul id="list">
<li>Dog</li>
<li>Cat</li>
<li>Hamster</li>
<li>Fish</li>
<li>Chicken</li>
<li>Pig</li>
<li>Cow</li>
<li>Giraffe</li>
<li>Elephant</li>
<li>Tiger</li>
</ul></pre>
<p>There’s one more piece we’ll need to add to get our HTML talking to our JavaScript, but for now we’re done.</p>
<p><a href="https://medium.com/@cgustin/tutorial-simple-search-filter-with-vanilla-javascript-fdd15b7640bf">Website</a></p>