DOM Basics

Creating DOM Elements and Fragments

The DOM is built starting with an element, typically the BodyElement which is obtained easily as follows:

import io.kweb.*
import io.kweb.dom.element.*

fun main() {
  Kweb(port = 16097) {
     val body : BodyElement = doc.body
 }
}

Let’s create a button element as a child of the body element, we do this using the .new function (which is supported by all Element types):

import io.kweb.*
import io.kweb.dom.element.*

fun main() {
  Kweb(port = 16097) {
     doc.body.new {
         button().text("Click Me!")
     }
   }
 }

If you assign the button element to a val then you can also modify its attributes:

Or delete it:

button.delete()

Reading from the DOM

Kweb can also read from the DOM, in this case the value of an <input> element:

import io.kweb.Kweb
import io.kweb.dom.element.creation.tags.*
import io.kweb.dom.element.events.on
import io.kweb.dom.element.new
import io.kweb.state.KVar
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.future.await
import kotlinx.coroutines.launch

fun main() {
    Kweb(port = 2395) {
        doc.body.new {
            val input: InputElement = input()
            input.on.submit {
                GlobalScope.launch {
                    val value = input.getValue().await()
                    println("Value: $value")
                }
            }
        }
    }
}

Note that input.getValue() returns a CompletableFuture<String>. This is because it can take up to several hundred milliseconds to retrieve from the browser, and we don’t want the application to block if it can be avoided. Here we use Kotlin’s very powerful coroutines features to avoid any unnecessary blocking.

Note

We discuss an even better way to read <input> values in a subsequent section.

Supported HTML tags

Kweb supports a significant subset of HTML tags like button(), p(), a(), table(), and so on. You can find a more complete list in the API documentation (scroll down to the Functions section). This provides a nice statically-typed HTML DSL, fully integrated with the Kotlin language.

If a tag doesn’t have explicit support in Kweb that’s not a problem. For example, here is how you might use the infamous and now-obsolete <blink> tag:

doc.body.new {
    val blink = element("blink").text("I am annoying!")
}

Extending Kweb to support new HTML tags

Adding support for new tags to Kweb is easy, take a look at the source. If you add some useful functionality please submit a pull request via Github, or just ask us and we’ll do our best to add support.

Further Reading

The Element class provides many other useful ways to interact with DOM elements.