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
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
Just cast
e
toHTMLElement
, so it gets all the properties you would expect.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:
Use
val
instead ofvar
in your code. It states for a fixed reference and allows some code optimizations. http://kotlinlang.org/docs/reference/properties.html#properties-and-fieldsDon't use nullable types like
Element?
if you don't need it. In this case you may be pretty sure about your DOM structure, sogetElementById("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: