Build HTML DOM trees
masterYou can build a DOM tree using JVM, JS, and WASM targets. The library provides extension functions like append and create to integrate with the browser's DOM API.
- Use
append { ... }on a DOM element to add new elements to an existing tree. - Use
create.tag { ... }to create a new element in memory without immediately attaching it to the document. - Use the
+operator (unary plus) to add text content inside a tag.
import kotlinx.browser.document
import kotlinx.browser.window
import kotlinx.html.a
import kotlinx.html.div
import kotlinx.html.dom.append
import kotlinx.html.dom.create
import kotlinx.html.p
fun main() {
val body = document.body ?: error("No body")
body.append {
div {
p {
+"Here is "
a("https://kotlinlang.org") { +"official Kotlin site" }
}
}
}
val timeP = document.create.p {
+"Time: 0"
}
body.append(timeP)
var time = 0
window.setInterval({
time++
timeP.textContent = "Time: $time"
return@setInterval null
}, 1000)
}