无法通过 HTMLCollectionOf<Elements> 进行交互 - 如何遍历此 HTMLCollectionOf<Elements> [复制]

Cannot interate through HTMLCollectionOf<Elements> - How can I iterate through this HTMLCollectionOf<Elements> [duplicate]

提问人:user14518063 提问时间:11/15/2023 更新时间:11/15/2023 访问量:32

问:

我可以看到带有以下代码的 HTMLCollectionOf

        let cards = document.getElementsByClassName(this.card_class) ;
        console.log( "CCC cards are ")
        console.log(cards)

这是我从 Chrome conole 那里得到的

但是我不能遍历这个HTMLCollection

我尝试使用不同的迭代方法(见下文),但没有一个会遍历集合。


        let cards = document.getElementsByClassName(this.card_class) ;
        console.log( "CCC cards are ")
        console.log(cards)

 console.log( "cards length with object,keys ",  Object.keys(cards).length)
 console.log( "cards length with cards.length ",  cards.length)

        Array.from(document.getElementsByClassName(this.card_class)).forEach(
            function(element, index, array) {
                console.log( "cccccc with Array.from(document.getElementsByClassName for")
                console.log(element.tagName);
            }
        );


        Array.prototype.forEach.call(cards, function(el) {
            // Do stuff here
            console.log( "cccccc in Array.prototype.forEach.call ")
            console.log(el.tagName);
        });
        const length = Object.keys(cards).length;
        for ( var i=0; i<length;i++){
            console.log( "cccccc in Array.prototype.forEach.call ")
            console.log(cards[i].tagName);
        }

        const s =  Array.from(cards);
        console.log(" Array.from(cards) is ")
        console.log(s)

        Array.from(cards).forEach( (e ) =>{
            console.log( "cccc  Array.from(cards).forEach( (e ) ")
            console.log(e)
        });

从镶边控制台图像中可以看出,没有一次迭代通过

你能让我知道我做错了什么吗?谢谢!

JavaScript 迭代

评论

0赞 code 11/15/2023
我无法重现。请包括一个最小的可重复示例
1赞 Nick Parsons 11/15/2023
你试图过早地遍历你的卡片。在运行和 时,您的卡片不存在,您需要在填充卡片后运行循环。getElementsByClassNameforEach()

答: 暂无答案