And this doesn't?
# javascript
m
And this doesn't?
r
Both forms work fine for me.
m
Interesting... Thank you. There might be other factors then. I'm developing a browser extension and I'm using the
build/distributions
folder as the root folder of my extension. Also, which browser are you using? I'm using Firefox.
r
I'm using Chrome
m
Yup, that's it. It's working on Chrome for me and not working on Firefox.
Firefox not throwing any errors.
r
It does work for me on Firefox, too
m
Interesting... I guess it's only not working as an extension then? Weird...
r
The
asList()
extension looks suspicious. It takes an external type
NodeList
and wraps it as a Kotlin
List
. Perhaps in your environment the
NodeList
is something different.
m
Yeah this
NodeList
has been failing me the whole afternoon. Is there any better way of dealing with this problem? By "this problem" I mean iterating over a
NodeList
safely while having access to the methods available to `HTMLElement`s.
r
You can try iterate with native forEach():
Copy code
document.querySelectorAll("div").asDynamic().forEach { div ->
    div.unsafeCast<HTMLDivElement>().style.background = "#ff0000"
    false
}
But I'm not sure this can be called "safely" 😉
m
Is there no other way to convert the
NodeList
into a Kotlin
List<Node>
?
So that I can use all the fancy Kotlin syntax sugar that
List
has to offer.
r
This works for me:
Copy code
val divs = js("Array").from(document.querySelectorAll("div")).unsafeCast<Array<HTMLDivElement>>().asList()
divs.forEach {
    it.style.background = "#ff0000"
}
m
Thank you, but also not working... 😕 I'd love to provide more feedback about the errors or something, but there simply are no errors.
e
try the usual JS "it's some array-like type but I need it to be a known array type" operation, translated to Kotlin?
Copy code
@JsName("Array")
external object JSArray {
    fun from(arrayLike: dynamic): Array<dynamic>
}
JSArray.from(document.querySelectorAll("div"))
m
Thank you very much, and sorry for the late response. This looks promising and I will give it a test this evening.