简体   繁体   English

HTMLCollection 从对象中获取每个元素

[英]HTMLCollection get every element from object

How can I make a loop for this collection to get every element?如何为这个集合创建一个循环来获取每个元素? I have tried these methods but they didn't work我已经尝试过这些方法,但没有奏效

const collection = document.getElementsByClassName('fc-daygrid-day-top') the type is an object

The First Method第一种方法

for(let arr of Array(collection)){console.log(Array(collection)[i])} // Doesn't work 

The second method第二种方法

var arr = [...collection]; // can't convert to array

May you know how to get every element from this object?你知道如何从这个对象中获取每个元素吗?

HTML

Here for(let arr of Array(collection)) array is created with only single element and that is HTMLCollection and cant iterate through.这里for(let arr of Array(collection))数组仅使用单个元素创建,即HTMLCollection并且无法迭代。 Array constructor need elements or size.数组构造函数需要元素或大小。 Fetched HTMLCollection is put into array as single element.获取的HTMLCollection作为单个元素放入数组中。 Better use spread operator to spread elements into array.更好地使用扩展运算符将元素传播到数组中。 for(let arr of Array(...elements))

You can either use for let of ... to iterate through HTMLCollection.您可以使用for let of ...来遍历 HTMLCollection。

 window.addEventListener('DOMContentLoaded', function(){ let elements = document.getElementsByClassName('test'); for(let element of elements) console.log(element.textContent); })
 <div class="test">1</div> <div class="test">2</div> <div class="test">3</div> <div class="test">4</div> <div class="test">5</div> <div class="test">6</div>

Or convert it to array with Array.from and iterate或者使用Array.from将其转换为数组并迭代

 window.addEventListener('DOMContentLoaded', function(){ let elements = document.getElementsByClassName('test'); Array.from(elements).map(element => console.log(element.textContent)) })

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

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