JAVASCRIPT

Filter a List of Items Dynamically with JavaScript

Implement client-side live search and filtering for an HTML list, allowing users to quickly find items by typing into an input field.

document.addEventListener('DOMContentLoaded', () => {
  const searchInput = document.getElementById('itemSearch');
  const itemList = document.getElementById('myList');

  if (searchInput && itemList) {
    const listItems = itemList.getElementsByTagName('li'); // Get all <li> elements

    searchInput.addEventListener('keyup', (event) => {
      const searchTerm = event.target.value.toLowerCase();

      Array.from(listItems).forEach(item => {
        const itemText = item.textContent.toLowerCase();
        if (itemText.includes(searchTerm)) {
          item.style.display = ''; // Show item
        } else {
          item.style.display = 'none'; // Hide item
        }
      });
    });
  }
});
How it works: This snippet demonstrates how to create a dynamic client-side filter for an unordered list. It listens for `keyup` events on an input field. As the user types, it iterates through each list item, checks if its text content includes the search term (case-insensitive), and then toggles its `display` style property to either show or hide the item. This provides a live search experience, enhancing usability for lists of data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs