Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  100] [ 1]  / answers: 1 / hits: 17893  / 4 Years ago, wed, october 21, 2020, 12:00:00

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);

More From » javascript

 Answers
48

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>




[#50591] Friday, October 2, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dylondaytond

Total Points: 92
Total Questions: 88
Total Answers: 96

Location: China
Member since Fri, Jan 15, 2021
3 Years ago
dylondaytond questions
Tue, Jun 22, 21, 00:00, 3 Years ago
Thu, May 7, 20, 00:00, 4 Years ago
;