Kotlin JS - Accessing HTML DOM properties

2k Views Asked by At

What is the canonical way to access HTML DOM properties in Kotlin. I don't see some of the dom properties like offsetHeight & offsetWidth exposed in the Element

var e : Element? = document.getElementById("text")
e.offsetHeight //Error
1

There are 1 best solutions below

2
On

Just cast e to HTMLElement, so it gets all the properties you would expect.

(e as HTMLElement).offsetHeight

It is not a feature of Kotlin, I found this in a normal JS documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight

ALSO

You are right to ask about a 'canonical' way to do things, since Kotlin is quite different from JavaScript internally. Here is how I would do your code snippet:

val e = document.getElementById("text")!! as HTMLElement
e.offsetHeight
  1. Use val instead of var in your code. It states for a fixed reference and allows some code optimizations. http://kotlinlang.org/docs/reference/properties.html#properties-and-fields

  2. Don't use nullable types like Element? if you don't need it. In this case you may be pretty sure about your DOM structure, so getElementById("text") must return an element, not a null. Put a null-assertion !! there to easy your mind. In case that your JS works with an unknown html, I would handle the situation better:

    val e = document.getElementById("text") as? HTMLElement ?: throw RuntimeException("the DOM has no 'text' id")