Filter search for <ul> Filter search for <ul> jquery jquery

Filter search for <ul>


Here is a input that filters a <ul> based on the value in pure JavaScript. It works by handling the onkeyup and then getting the <li>s and comparing their inner element .name with the filter text.

jsFiddle

enter image description here

var input = document.getElementById('input');input.onkeyup = function () {    var filter = input.value.toUpperCase();    var lis = document.getElementsByTagName('li');    for (var i = 0; i < lis.length; i++) {        var name = lis[i].getElementsByClassName('name')[0].innerHTML;        if (name.toUpperCase().indexOf(filter) == 0)             lis[i].style.display = 'list-item';        else            lis[i].style.display = 'none';    }}


So you have a collection of list items inside an unordered list like this.

<div class="some-input-field-class">   <input type="text" name="filter" id="filter">   <label for="filter">Filter Names</label></div><ul class="my-user-collection">  <li class="thumb selectable arrow light" style="margin-bottom:-5px;"  data-image="http://cdn.tapquo.com/lungo/icon-144.png">  <strong class="name">Peter <font data-count="0" style="position:relative;top:-2px;"> </font></strong>   <small class="description">Hi!</small>   </li>  ...</ul>

You can add this in your javascript file. But you will need to load the event listener too. You probably have a few events so just do what you need to do. Maybe add it to another function where you load the rest of your event listeners.

// Load the event listenerdocument.querySelector('#filter').addEventListener('keyup', filterNames);

Function to iterate through the li by targeting the class, iterate through the array since we use querySelectorAll and NOT getElementByID. -1 means no match.

function filterNames(e) {  const text = e.target.value.toLowerCase();  document.querySelectorAll('.selectable').forEach(    function(name) {      let item = name.firstChild.textContent;      if (item.toLowerCase().indexOf(text) != -1) {        name.style.display = 'block';      } else {        name.style.display = 'none';      }    }  );}