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.

2

There are 2 answers

4
deive On BEST ANSWER

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"
        }
    }
}
2
ker2x On

I had a similar problem, the solution I found was to create an element (and get its reference immediately) :

myElement = document.createElement("canvas") as HTMLCanvasElement
// add some more properties at will
myElement.width = 800
myElement.height = 600

then append the newly created element :

document.body!!.append(myElement) 

you have your reference, and you have your referenced element inserted.

Now you can access all the functions you want (in my case the canvas api provided by HTMLCanvasElement) by simply doing myElement.someAPIFunction()