I'm currently working on a basic filter using Vanilla Javascript and CSS.
Whenever a user chooses a category, the articles that do not belong to that category are hidden by adding the class .hide
. My goal is to then remove these hidden articles from the DOM completely, and later display them again when the user selects the relevant category.
The filtering mechanism successfully adds and removes the class .hide
. However, the problem arises when the hidden articles are removed - they do not reappear upon selection.
Here's the JS logic:
const filterBox = document.querySelectorAll('.js-article');
document.querySelector('.js-filter-list').addEventListener('click', (event) => {
if (event.target.tagName !== 'BUTTON') return false;
let filterClass = event.target.dataset['filter'];
filterBox.forEach(elem => {
elem.classList.remove('hide');
elem.parentNode.appendChild(elem);
if (!elem.classList.contains(filterClass) && filterClass !== 'all') {
elem.classList.add('hide');
elem.parentNode.removeChild(elem);
}
});
});
This is how the HTML structure looks like:
<div class="c-filter__list js-filter-list">
<button class="c-filter__list-item is-active js-filter-item" data-filter="all">All</button>
<button class="c-filter__list-item o-font-title js-filter-item" data-filter="cat-1">Cat 1</button>
<button class="c-filter__list-item o-font-title js-filter-item" data-filter="cat-2">Cat 2</button>
<button class="c-filter__list-item o-font-title js-filter-item" data-filter="cat-3">Cat 3</button>
<button class="c-filter__list-item o-font-title js-filter-item" data-filter="cat-4">Cat 4</button>
</div>
<article class="js-article cat-1"></article>
<article class="js-article cat-2"></article>
<article class="js-article cat-2 cat-3"></article>
<article class="js-article cat-1" ></article>
<article class="js-article cat-4"></article>
<article class="js-article cat-3 cat-4"></article>
...
Your assistance is much appreciated!