Skip to main content

Filtering Elements in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to filter elements in JavaScript DOM using simple techniques to improve the readability and user experience of your web applications.

Example: Filtering List Items Containing a Specific Word

Let's consider the following unordered list with unordered items:

<ul id="fruit-list">
<li>Orange</li>
<li>Apple</li>
<li>Banana</li>
<li>Green Apple</li>
<li>Grapes</li>
</ul>

We will now filter the list items containing the word "Apple":

const fruitList = document.getElementById('fruit-list');
const listItems = Array.from(fruitList.getElementsByTagName('li'));

const filteredItems = listItems.filter(item => item.textContent.includes('Apple'));

fruitList.innerHTML = '';

filteredItems.forEach(item => {
fruitList.appendChild(item);
});

After executing this code, the updated HTML structure will be:

<ul id="fruit-list">
<li>Apple</li>
<li>Green Apple</li>
</ul>

In this example, we used the following steps to filter the list items containing the word "Apple":

  1. Get the list element using getElementById.
  2. Get the list items and convert them to an array using Array.from.
  3. Filter the list items using the filter method and the includes function for string comparison.
  4. Clear the original list items using innerHTML.
  5. Append the filtered list items to the list using appendChild.
Live Playground, Try it Yourself

Conclusion

In this tutorial, we have learned how to filter elements in JavaScript DOM using simple techniques. Filtering elements can improve the readability and user experience of your web applications, making it easier for users to find and navigate through the content.