Search code examples
jquerygroovygeb

Check for same attribute in a number of HTML elements using Groovy script


Hi I am new to Groovy.

I want to drill down into DOM structure and retrive a set of elements and check if those elements have a particular attribute.

Below is the statement I used to check for the attributes-

assert $("#myID > div > div > div > p > a > span").attr("class").contains("my-class")

$("#myID > div > div > div > p > a > span") returns 3 span elements and therefore the above statement fails and throws an error -

geb.error.SingleElementNavigatorOnlyMethodException: Method getAttribute(java.lang.String) can only be called on single element navigators but it was called on a navigator with size 3. Please use the spread operator to call this method on all elements of this navigator or change the selector used to create this navigator to only match a single element.

How do I loop through all the returned span and check if all of them have the my-class attribute?

Thanks in advance!


Solution

  • So, since you use Groovy, you can use for example a foreach to iterate through your elements:

    def containsAttr = true
    $("#myID > div > div > div > p > a > span").each { element ->
        if (! element.attr("class").contains("my-class")) {
            containsAttr = false
        }
    }
    assert containsAttr == true
    

    important is that you recognize the $()-Selection of elements as a collection. When you progress with your groovy knowledge, you will find even groovier ways to iterate through the collection, but I think for now, the each loop shows best how it can be done.

    See http://docs.groovy-lang.org/next/html/documentation/working-with-collections.html for more details on collections.

    PS: a drawback of the code given by me is that the power-assertion will not reveal too mich info when it fails.