1

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?

glennsl
  • 28,186
  • 12
  • 57
  • 75
Shaac
  • 195
  • 14

1 Answers1

1

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.

glennsl
  • 28,186
  • 12
  • 57
  • 75
  • 1
    Thanks, it works. Since the elements I am working with are div, I used: `Js.Opt.bind (Dom.CoerceTo.element node) (fun elem -> if (Js.to_string elem##.tagName) <> "DIV" then Js.Opt.empty else Js.Opt.return (Js.Unsafe.coerce elem))` – Shaac Jul 01 '19 at 23:32