All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dom.DomJS.kt Maven / Gradle / Ivy

There is a newer version: 1.0.7
Show newest version
package kotlin.dom

import org.w3c.dom.*
import org.w3c.dom.DOMTokenList
import org.w3c.dom.HTMLCollection
import org.w3c.dom.HTMLElement
import java.util.*

/** Searches for elements using the element name, an element ID (if prefixed with dot) or element class (if prefixed with #) */
operator fun Document?.get(selector: String): List {
    return this?.querySelectorAll(selector)?.asList()?.filterElements() ?: emptyList()
}

/** Searches for elements using the element name, an element ID (if prefixed with dot) or element class (if prefixed with #) */
operator fun Element.get(selector: String): List {
    return querySelectorAll(selector).asList().filterElements()
}

private class HTMLCollectionListView(val collection: HTMLCollection) : AbstractList() {
    override val size: Int get() = collection.length

    override fun get(index: Int): HTMLElement =
            when {
                index in 0..size - 1 -> collection.item(index) as HTMLElement
                else -> throw IndexOutOfBoundsException("index $index is not in range [0 .. ${size - 1})")
            }
}

public fun HTMLCollection.asList(): List = HTMLCollectionListView(this)

private class DOMTokenListView(val delegate: DOMTokenList) : AbstractList() {
    override val size: Int get() = delegate.length

    override fun get(index: Int) =
            when {
                index in 0..size - 1 -> delegate.item(index)!!
                else -> throw IndexOutOfBoundsException("index $index is not in range [0 .. ${size - 1})")
            }
}

public fun DOMTokenList.asList(): List = DOMTokenListView(this)
internal fun HTMLCollection.asElementList(): List = asList()




© 2015 - 2024 Weber Informatics LLC | Privacy Policy