嗨,我在过滤 HTML 集合时遇到问题。我获得了作为 html 集合的类列表。其中一个类有 .active 类。我需要从此列表中删除所有其他类(class),并在事件类(class)之后只留下下一个。请问该怎么做?
我的 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.
我的代码:let allChaptersItems= document.getElementsByClassName("chapter-list-item");
let activeChapter = document.getElementsByClassName("active");
console.log(activeChapter);
console.log(allChaptersItems);
最佳答案
您可以使用 :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)
}
<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>
但是,如果您已经有一些元素并想要过滤它们,您可以 convert to array他们使用
Array#filter
检查是否 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>
关于javascript - 如何在 JavaScript 中过滤 HTML 集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64457597/