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);
Advertisement
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>
Note that document.querySelectorAll()
returns a NodeList, instead of an HTMLCollection. The difference is that the HTMLCollection is live and will change with changes to the DOM, while the NodeList is not. For full explanation see Difference between HTMLCollection, NodeLists, and arrays of objects Both a NodeList and an HTMLCollection are array-like objects and can be treated the same in most cases.
However, if you already have some elements and want to filter them, you can convert to array and then use Array#filter
to check if the “active” class is not in the list of classes using .contains()
:
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>