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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay