DEV Community

artydev
artydev

Posted on

2

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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook