0

I tried to build a filter for some posts. When a year is selected the other year should be removed from the page. But only the half of the unselected year posts gets deleted. What am I doing wrong?

var filter2020 = document.getElementById('filter20');
var filter2021 = document.getElementById('filter21');
var posts = document.getElementsByClassName('article');

if (filter2020) {
  for (item of posts) {
    if (item.dataset.year == "Y2020") {
      item.remove();
    } else {
      console.log("no")
    }
  }
} else if (filter2021) {
  for (item of posts) {
    if (item.dataset.year == "Y2021") {
      item.remove();
    } else {
      console.log("no")
    }
  }
} else {

}
<div class="row filtered-news">
  <div class="article col-lg-4" data-year="Y2021"> </div>
  <div class="article col-lg-4" data-year="Y2020"> </div>
</div>
fevo2
  • 11
  • 3
  • 1
    I made a snippet for you. It gives errors. Please update to make a [mcve] - seems you need some checkboxes? – mplungjan Jun 27 '22 at 12:39
  • Here's an alternative, I'm not sure if it might help. Instead of getting all posts then filtering, just get posts that already satisfy the filter... – coolDog Jun 27 '22 at 12:43
  • Is filter20 si button – Gulshan Prajapati Jun 27 '22 at 12:43
  • 1
    See [this SO answer](https://stackoverflow.com/a/71999920): Instead of iterating a live collection, convert it to an array and iterate through that: `posts = [...document.getElementsByClassName('article')]`. – collapsar Jun 27 '22 at 12:47
  • 1
    *getElementsByClassName* returns a live node list. Each time an element is removed, the next elements shuffle down to fill the empty slot. *for..of* iterates over a collection the same as a *for* loop, so you end up only removing every second element. – RobG Jun 27 '22 at 12:52
  • 1
    or better: `document.querySelectorAll('.article').forEach(post=> post.hidden = postdataset.year === whatever)` – mplungjan Jun 27 '22 at 12:53
  • @mplungjan Thanks for that, your solution was so much smarter and shorter than my approach. I'm still shaky with js. Thanks as well to everyone else. – fevo2 Jun 27 '22 at 13:16
  • I missed a dot though – mplungjan Jun 28 '22 at 09:12

0 Answers0