Search code examples
javascriptdomreason

How do I set a DOM element's text in Reason?


I'm currently learning Reason. Here's what I've written so far:

[@bs.val] external document: Dom.document = "document";
[@bs.send]
external get_element_by_id: (Dom.document, string) => Js.nullable(Dom.node) =
  "getElementById";

let our_node =
  Js.Nullable.toOption(get_element_by_id(document, "do_something"));

let d = Js.Date.make();
switch (our_node) {
| None => Js.log("can't find the output element")
| Some(nnode) => nnode.textContent = Js.Date.toString(d)
};

I want to set a DOM node's text to current date. However, I've received an error: The record field textContent can't be found. Looking into node_modules/bs-platform/lib/ocaml/dom.ml, I see that, indeed, there isn't a textContent field in Dom.node or Dom.htmlElement or the like. How do I set the text?


Solution

  • I have found a solution by doing a bit of digging in bs-webapi code.

    Apparently you just need to add a bs-set directive:

    [@bs.set] external setTextContent: (Dom.htmlElement, string) => unit = "textContent";
    

    It's explained more thoroughly in "Property access" docs for BuckleScript.