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":
- Get the list element using
getElementById
. - Get the list items and convert them to an array using
Array.from
. - Filter the list items using the
filter
method and theincludes
function for string comparison. - Clear the original list items using
innerHTML
. - 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.