bs-webapi - 如何循环 Dom.nodeList?

bs-webapi - How to loop over Dom.nodeList?

以下内容无效,因为 sides 是 Dom.nodeListDomTokenList.forEach 期望 Dom.domTokenList.

open Bs_webapi.Dom;

external length : Dom.nodeList => int = "" [@@bs.get];

let sides = Document.querySelectorAll "#carousel > figure" document;

DomTokenList.forEach (fun item _ => print_endline item) (sides);

转自 Reason Discord,由@anmonteiro 提供:

Js.Array.forEach Js.log (NodeList.toArray sides);

这里是一个示例,说明如何 setAttribute 中的每个元素 NodeList。请注意,Element.ofNode 可用于将 Dom.node 转换为 option Dom.element

open Bs_webapi.Dom;

external length : Dom.nodeList => int = "" [@@bs.get];

let sides = Document.querySelectorAll "#carousel > figure" document;

Js.Array.forEachi
  (fun side index =>
    switch (Element.ofNode side) {
    | Some element =>
      Element.setAttribute "style" "some style here" element
    | None => ()
    }
  )
  (NodeList.toArray sides)

https://bucklescript.github.io/bucklescript/api/Js_array.html#VALforEach