Written by Sean Behan on Tue Jan 30th 2018

The basic approach is to use the document.querySelectorAll to match certain elements, then manually set the display property to 'none' or 'block' (or 'inline-block') to hide or show it. Using the match method allows us to detect whether or not the search term is contained in the element's innerText attribute.

Here is the code

<input type="text" onkeyup="filter(this)"/>

<div class="row">apple</div>
<div class="row">banana</div>
<div class="row">carrot</div>

<script>
function filter(e){
    search = e.value.toLowerCase();
    console.log(e.value)
    document.querySelectorAll('.row').forEach(function(row){
        text = row.innerText.toLowerCase();
        if(text.match(search)){
            row.style.display="block"
        } else {
            row.style.display="none"
        }
    })
}
</script>

Here is a Data URL to see a working example of the approach.


Tagged with..
#javascript #html #vanilla #js

Just finishing up brewing up some fresh ground comments...