kotlin-jskotlinx-html

When using kotlinx.html's DSL to create HTML, (how) is it possible to refer to the created elements?


I'm writing a browser app in Kotlin/JS, and I'm using kotlinx.html's DSL to generate some of the HTML. For (a simple) example:

(window.document.body!! as Node).append {
    p {
        +"Some text"
    }
    p {
        +"Click here"
        onClickFunction = { event ->
            <Do some stuff here...>
        }
    }
}

Now my problem is I want to be able to refer to the elements created by this code. For example, say when the user clicks on the second p element (where there's a click event handler) I want to do something with the first p element (e.g. change its text). Is there an elegant way to do that?

I know I can somehow find that element (e.g. by giving it an ID and then looking for it, or by relying on its position or something), and that I can do it either within the event handler or, if I prefer, in some other code that will be run after the elements are created – but still as part of initialisation – and will save a reference to the element in some variable that the event handler can then use. But doing something like that feels like a workaround when my code defines that element right there, and so I'm looking for a way to get a reference to that element as part of the process building it if that's at all possible.


Solution

  • The DSL methods also return the DOM object they create, so you can assign them to a variable and use that later:

    (window.document.body!! as Node).append {
        val firstP = p {
            +"Some text"
        }
        p {
            +"Click here"
            onClickFunction = { event ->
                firstP.textContent = "Clicked"
            }
        }
    }