How to filter HTMLCOLLECTION in js? [closed]

Tags:



Hi I have problem with filtering HTML collection. I obtained list of classes as html collection. One of those class have .active class. I need to remove all other classes from this list and left only next one AFTER active class. Please how to do that?

Example of my list:

HTMLCollection []
0: div.chapter-list-item.seen
1: div.chapter-list-item.seen
2: div.chapter-list-item.seen
3: div.chapter-list-item.seen
4: div.chapter-list-item.active.seen
5: div.chapter-list-item.seen
6: div.chapter-list-item.seen
7: div.chapter-list-item.seen
8: div.chapter-list-item.

My code:

let allChaptersItems= document.getElementsByClassName("chapter-list-item");
let activeChapter = document.getElementsByClassName("active");
console.log(activeChapter);
console.log(allChaptersItems);

Answer

You can directly query to get the items you want using the :not() selector to prevent matching items you don’t want:

const chapters = document.querySelectorAll(".chapter-list-item:not(.active)");

console.log("Found elements:")
for (const chapter of chapters) {
  console.log(chapter.textContent, chapter.className)
}
<div class="chapter-list-item seen">One</div>
<div class="chapter-list-item seen other">Two</div>
<div class="chapter-list-item seen active">Three</div>
<div class="chapter-list-item seen">Four</div>

However, if you already have some elements and want to filter them, you can convert to array and them use Array#filter to check if the “active” class is not in the list of classes:

const existingElements = document.querySelectorAll(".chapter-list-item");

const chapters = Array.from(existingElements)
  .filter(chapter => !chapter.classList.contains("active"))

console.log("Found elements:")
for (const chapter of chapters) {
  console.log(chapter.textContent, chapter.className)
}
<div class="chapter-list-item seen">One</div>
<div class="chapter-list-item seen other">Two</div>
<div class="chapter-list-item seen active">Three</div>
<div class="chapter-list-item seen">Four</div>


Source: stackoverflow