kotlinx.html icon indicating copy to clipboard operation
kotlinx.html copied to clipboard

get underlying HtmlElement

Open robstoll opened this issue 6 years ago • 7 comments

I currently use the following hack to retrieve the underlying HtmlElement:

div { 
  val div = getUnderlyingHtmlElement()
  div.asDynamic().someVar = xyZ
}

where the function is defined as follows:

fun HTMLTag.getUnderlyingHtmlElement(): HTMLElement {
    var d = this.consumer.asDynamic()
    if (d.downstream != null) {
        d = d.downstream
    }
    val arr = d.path_0.toArray() as Array<HTMLElement>
    return arr[arr.size - 1]
}

I don't know if I am the only one having such use cases but if not, maybe worth considering to add it to the library (maybe a property named htmlElement, I am using the long name on purpose)

robstoll avatar May 08 '18 08:05 robstoll

You can try to use inject instead however it's functionality is quite limited but could be enough for some cases

https://github.com/Kotlin/kotlinx.html/wiki/Injector https://github.com/Kotlin/kotlinx.html/blob/bb9fd5b1745f6e4281baf55b4b8e2b3a58932e65/js/src/test/kotlin/injector.kt#L70-L69

cy6erGn0m avatar May 08 '18 08:05 cy6erGn0m

I'll stick to my hack. Feel free to close this issue whenever you want, it's not really an issue for me, I just wanted to share my way of doing things.

robstoll avatar May 08 '18 08:05 robstoll

Keep in mind that the hack is not safe as both path_0 and downstream are unstable names. First of all private fields could be simply renamed without any notice. The other potential issue is that suffix _0 is generated by the compiler according to the current mangling rules that could be amended as well in the future. Therefore I'd say this hack will only go for PoC or prototyping purposes

cy6erGn0m avatar May 08 '18 13:05 cy6erGn0m

You're absolutely right, It will probably break at some point and when it does then I can only blame myself. I would not recommend someone else to use it, I hoped there is a better way of doing the same. You could provide a stable version because you probably have access to both downstream and path (or is path from ArrayList, I don't remember).

robstoll avatar May 08 '18 14:05 robstoll

@robstoll I have the exact same use case and need to access the underlying org.w3c.dom.HTMLElement. I thought about implementing my own kotlinx.html.TagConsumer which delegates to kotlinx.html.dom.JSDOMBuilder and get access to the element somehow.

It would be great if we could get access to the element w/o relying on unsafe hacks

hpehl avatar May 19 '20 07:05 hpehl

@hpehl Could you share your attempts? :)

seungha-kim avatar Aug 07 '20 17:08 seungha-kim

@seungha-kim not really 😐

Instead, I use a workaround: I mark my tags with special data- attributes and use CSS selectors to get the DOM element later on.

hpehl avatar Aug 24 '20 16:08 hpehl