DEV Community

artydev
artydev

Posted on

A simple way to filter list with data attributes

<script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/faker.js"></script>
<input type="text" id="filter" class="input" placeholder="filter" value="">
Enter fullscreen mode Exit fullscreen mode
const ul = document.createElement('ul');

ul.style.display = 'none';
ul.classList.add('content');

const listItems = Array.from({ length:  1000 }, () => {
  const name = faker.name.findName();
  const li = document.createElement('li');
  li.textContent = name;
  li.dataset.name = name;
  ul.appendChild(li)
  return li;
});

document.body.appendChild(ul);

window.filter.addEventListener('input', (event) => {
  const inputValue = event.target.value.toLowerCase().trim();
  ul.style.display = inputValue ? "block" : "none"; 
  listItems.forEach(item => {
    const attribute = item.dataset.name.toLowerCase();
    item.style.display = attribute.includes(inputValue) ? 'block' : 'none';
  });
});
Enter fullscreen mode Exit fullscreen mode

You can test it here : Demo

Top comments (0)