diff --git a/stdlib/ktSrc/dom/Dom.kt b/stdlib/ktSrc/dom/Dom.kt index 669678cf825..50751901975 100644 --- a/stdlib/ktSrc/dom/Dom.kt +++ b/stdlib/ktSrc/dom/Dom.kt @@ -74,22 +74,36 @@ set(value) { // Helper methods +/** Searches for elements using the element name, an element ID (if prefixed with dot) or element class (if prefixed with #) */ +fun Document?.get(selector: String): List { + val root = this?.getDocumentElement() + return if (root != null) { + root.get(selector) + } else { + Collections.EMPTY_LIST as List + } +} + +/** Searches for elements using the element name, an element ID (if prefixed with dot) or element class (if prefixed with #) */ +fun Element.get(selector: String): List { + if (selector.startsWith(".")) { + // TODO filter by CSS style class + } else if (selector.startsWith("#")) { + // TODO lookup by ID + } + // TODO assume its a vanilla element name + return this.getElementsByTagName(selector).toElementList() +} + +/** Returns the children of the element as a list */ inline fun Element?.children(): List { return this?.getChildNodes().toList() } -inline fun Element?.elementsByTagName(name: String?): List { - return this?.getElementsByTagName(name).toElementList() -} - inline fun Element?.elementsByTagNameNS(namespaceUri: String?, localName: String?): List { return this?.getElementsByTagNameNS(namespaceUri, localName).toElementList() } -inline fun Document?.elementsByTagName(name: String?): List { - return this?.getElementsByTagName(name).toElementList() -} - inline fun Document?.elementsByTagNameNS(namespaceUri: String?, localName: String?): List { return this?.getElementsByTagNameNS(namespaceUri, localName).toElementList() } diff --git a/testlib/test/dom/DomBuilderTest.kt b/testlib/test/dom/DomBuilderTest.kt index dea799d0dae..2548268e1d8 100644 --- a/testlib/test/dom/DomBuilderTest.kt +++ b/testlib/test/dom/DomBuilderTest.kt @@ -11,6 +11,10 @@ class DomBuilderTest() : TestSupport() { fun testBuildDocument() { var doc = createDocument() + assert { + doc["grandchild"].isEmpty() + } + doc.addElement("foo") { id = "id1" style = "bold" @@ -27,8 +31,7 @@ class DomBuilderTest() : TestSupport() { } println("builder document: ${doc.toXmlString()}") - - val grandChild = doc.elementsByTagName("grandChild").first + val grandChild = doc["grandChild"].first if (grandChild != null) { println("got element ${grandChild.toXmlString()} with text '${grandChild.text}`") assertEquals("Hello World!", grandChild.text)