javascript - 如何在 JavaScript 中过滤 HTML 集合?

标签 javascript

嗨,我在过滤 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/

相关文章:

javascript - 在 JavaScript 中安全地缓存密码以备后用

javascript - if 语句中的函数执行多次

Javascript 计时器和页脚 div

javascript - 加载页面时 jQuery 代码不起作用

javascript - SAPUI5处理对话框中的输入

javascript - Angular JS 中站点范围配置的设计模式

javascript - JSON.parse 没有预期的行为

javascript - Angular JS 方法 - 一个依赖于另一个的结果

javascript - Angular2 onbeforeunload

JavaScript 范围内的 eval,未定义的值