4

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.

Antoine
  • 1,782
  • 1
  • 14
  • 32
  • 1
    To add to the 2 other answers, which are correct, a pull request on js_of_ocaml to add this method would be welcome. :) – Drup May 22 '15 at 20:34

3 Answers3

1

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

matrixanomaly
  • 6,627
  • 2
  • 35
  • 58
1

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.

antron
  • 3,749
  • 2
  • 17
  • 23
1

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

Çağdaş Bozman
  • 2,537
  • 16
  • 21