繁体   English   中英

遍历元素并检查香草javascript中的子类是否上课

[英]Loop through elements and check children for class in vanilla javascript

我试图遍历具有相同类的元素,以查看按钮是否在特定元素内具有特定类。 我知道如何在jQuery中完成此操作,但是该项目没有jQuery,所以必须使用香草JS完成...我对此并不熟悉。

    let boardItems = document.getElementsByClassName("item--product");
    for (let i = 0; i < boardItems.length; i++) {
        if(boardItems.children.classList.contains('board-item-selected')){
            console.log(i);
        }
    }

我想要获得的确是在子级中包含类的每个项目的索引号。

HTMLCollection转换为HTMLElement数组,并解析每个元素的类列表。

 let htmlCollection = document.getElementsByClassName("item--product"); let array = [].slice.call(htmlCollection) for (let i = 0; i < array.length; i++) { if(array[i].classList.contains("board-item-selected")){ console.log("The index of the board-item-selected: " + i) } } 
 <div class="item--product"></div> <div class="item--product"></div> <div class="item--product board-item-selected"></div> <div class="item--product"></div> <div class="item--product board-item-selected"></div> <div class="item--product"></div> <div class="item--product"></div> 

您正在访问整个列表,而不是数组。

尝试将第3行更改为if(boardItems[i].classList.contains('board-item-selected')) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM