Skip to content
Sergey Mashkov edited this page Jul 6, 2015 · 4 revisions

DOM trees

With kotlinx.html you can build DOM trees and append them to a document. This functionality is available for both Kotlin-JVM and Kotlin-JavaScript.

To begin building a tree you need a document. In Kotlin2js there is a kotlin.browser.document available so you can start with it. On JVM you can create Document by hand and use it.

So if we have a document we can start building like this

import kotlinx.html.*
import kotlinx.html.dom.*

val myDiv = document.create.div {
    p { +"text inside" }
}

Please note that the code above will produce element instance and no elements will be added to the document. The other notice that it returns type HTMLElement (not HTMLDivElement). If we use it with browser we can import another package kotlinx.html.js instead of kotlinx.dom.* so we will get myDiv: HTMLDivElement that is much better for further manipulations.

If we want to create and then append tree to the document we can use append function on the node to be parent of created tree:

fun appendTab(containerDiv: HTMLDivElement) {
    containerDiv.append.div {
        p { +"tab" }
        div {
            //...
        }
    }
}