Search code examples
reasonbucklescriptbs-webapi

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


The following won't work since sides is a Dom.nodeList and DomTokenList.forEach expects a 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);

Solution

  • Paraphrased from the Reason Discord, courtesy of @anmonteiro:

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

    Here is an example of how to setAttribute for each element in a NodeList. Note, Element.ofNode can be used to convert a Dom.node to 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