Equivalent of document.getElementsByClassName

1k views Asked by At

I can't find a js_of_ocaml equivalent of document.getElementsByClassName. What is the canonical way to do?

EDIT : I'm using js_of_ocaml v2.5.

3

There are 3 answers

0
antron On

You can write a function that will call it directly:

let getElementsByClassName (name : Js.js_string Js.t)
    : Dom_html.element Dom.nodeList Js.t =
  Js.Unsafe.meth_call
    Dom_html.document "getElementsByClassName" [|Js.Unsafe.inject name|]

The signature is based on the signature of Dom.document##getElementsByTagName. The type constraints are necessary for type-safe usage.

You can use it like this:

getElementsByClassName (Js.string "control")

You may want to change the interface so it takes an OCaml string, in the style of the Dom_html.getElementById. Then, maybe you should also make it return an OCaml list.

0
matrixanomaly On

It doesn't seem to exist.

The closest I can find to that is by using the className attribute of DOM_html elements (docs) and DOM_svg elements (docs). You can then iterate through the collection and get the element you want.

This was taken from method index which I searched through.

The DOM document class however does have getElementById and getElementBy tag name as shown here.

method getElementById : Js.js_string Js.t -> 'element Js.t Js.opt Js.meth

method getElementsByTagName : Js.js_string Js.t -> 'element nodeList Js.t Js.meth

1
Çağdaş Bozman On

I needed that function too some weeks ago, so I made a PR https://github.com/ocsigen/js_of_ocaml/pull/312