Each div has the same class and we query for a HTMLCollection using ‘ getElementsByClassName ‘. Here are 4 ways to convert the returned HTMLCollection to an array.
2021-01-11
I used a vanilla JavaScript for the frontend and a homegrown Rails API for the backend! 在 JavaScript 中使用. 在 JavaScript 中,为了获取给定的 HTMLCollection 的元素,可以使用方括号语法来代替直接调用 item () 或 namedItem () 方法。. 在方括号中,数值如同 item () ,字符串值如同 namedItem ()。. 例如,假定在文档中有一个
The HTMLCollection in the HTML DOM is live, meaning when the document is changed it will be automatically updated. NodeList objects are collections of nodes returned by properties such as Node. The HTMLCollection doc does, however reference the NodeList doc, which does mention iteration: Don’t be tempted to use for…in or for each…in to enumerate the items in the list, since that will also The children property returns a collection of an element's child elements, as an HTMLCollection object. The elements in the collection are sorted as they appear in the source code and can be accessed by index numbers. The index starts at 0. The only reason to convert an HTMLCollection and NodeList to an Array is, if you want to use higher order functions like forEach, map, filter and reduce. There are a lot of use cases, for instance, let's say you have elements that contain a data-src property along with lazy-load class.