Search code examples
ocamljs-of-ocaml

How to set an attribute of a Dom element


I have created a td element with a call such as:

  let td = Dom_html.createTd doc in

I would now like to set an attribute on this object. I have tried this:

  td#setAttribute (Js.string "colspan") (Js.string "4")

But I get the error:

Error: This expression has type Dom_html.tableCellElement Js.t
It has no method setAttribute


Solution

  • Simple dash # is used to access method of OCaml object.

    Js_of_ocaml has a special syntax (##) to deal with Javascript object. see http://ocsigen.org/js_of_ocaml/2.4/manual/library

    To set an attribute of a dom element:

    td##setAttribute(Js.string "key", Js.string "val")
    

    In you case you should rather use :

    td##colSpan <- 4
    

    The double dash ## will translate JavaScript field access. The previous statement translates to td.colSpan = 4.

    The type parameter 'a in 'a Js.t is a phantom type used by the type checker to check JavaScript field access. see http://ocsigen.org/js_of_ocaml/2.4/api/Dom_html.tableCellElement-c in your case.