【问题标题】:How to filter HTML Collection in JavaScript?如何在 JavaScript 中过滤 HTML 集合?
【发布时间】:2021-02-04 00:22:33
【问题描述】:

您好,我在过滤 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.

我的代码:

let allChaptersItems= document.getElementsByClassName("chapter-list-item");
let activeChapter = document.getElementsByClassName("active");
console.log(activeChapter);
console.log(allChaptersItems);

【问题讨论】:

    标签: javascript


    【解决方案1】:

    您可以使用: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>

    【讨论】:

    • 一个对 OP 来说可能无关紧要的挑剔:他们有一个实时 HTMLCollection,qSA 将返回一个静态 NodeList。
    猜你喜欢
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 2016-12-20
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多