domocamljs-of-ocaml

Get children of Dom_html.element


In js_of_ocaml, is it possible to get the child nodes of Dom_html.element?

I know that the class inherits Dom.node, and thus has the childNodes method. But since it is a method from Dom.node, it returns values of Dom.node types. And I need those nodes to still be Dom_html.element, or else most methods will not be available.

Since downcasting is not possible in OCaml, I do not find any possible solution for this issue. Am I missing something or is this really impossible?


Solution

  • childNodes cant't be typed as a collection of Dom_html.elements because the nodes returned can, and are likely to, include nodes that are not elements, such as text nodes.

    The DOM standard defines a property children on Element which would only return the elements, but that still wouldn't get you to Dom_html.element. And unfortunately it also does not seem to be included in JSOO's Dom.element.

    You can use the element function of Dom.CoerceTo to safely coerce Dom.nodes to Dom.elements, but I don't think there is any generally reliable way to go from Dom.element to Dom_html.element, because the DOM is unfortunately too dynamically typed.

    You might have to check the tagName manually and (unsafely) cast it using Js.Unsafe.coerce.