如何在js中过滤HTMLCOLLECTION?

You*_* L. 5 javascript

嗨,我在过滤 HTML 集合时遇到问题。我获得了类列表作为 html 集合。其中一类具有 .active 类。我需要从此列表中删除所有其他类,并在活动类之后只留下下一个类。请问怎么做呢?

我的清单示例:

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.
Run Code Online (Sandbox Code Playgroud)

我的代码:

let allChaptersItems= document.getElementsByClassName("chapter-list-item");
let activeChapter = document.getElementsByClassName("active");
console.log(activeChapter);
console.log(allChaptersItems);
Run Code Online (Sandbox Code Playgroud)

VLA*_*LAZ 8

您可以使用:not()选择器直接查询以获取您想要的项目,以防止匹配您不想要的项目:

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

console.log("Found elements:")
for (const chapter of chapters) {
  console.log(chapter.textContent, chapter.className)
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

但是,如果您已经有一些元素并想要过滤它们,您可以转换为数组,它们用于Array#filter检查“活动”类是否不在类列表中

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)
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 一个可能对 OP 来说并不重要的挑剔:他们有一个实时 HTMLCollection,qSA 将返回一个静态 NodeList。 (2认同)