BruceyBandit
BruceyBandit

Reputation: 4324

Iterate through each element in java to see if it's displayed

I am new to Java and would like assistance on the best way to perform the following:

I wanted to grab all of the elements that belongs to a class but I want to perform a count on how many of these elements are displayed. I have set up the code to create an int counter, the findelements and the assertion but basically my question is how in java do you create a for loop to simply check if an element within the elements list is displayed, then +1 on the count?

    int testNumber = 0;
    List<WebElement> testItems = _driver.findElements(By.className("test"));

    //Loop each element from the list and if it's displayed then +1 for test Number         

    Assert.assertEquals(testNumber, 4,
            "Mismatch between the number of test items displayed");

Upvotes: 0

Views: 584

Answers (1)

Zabuzard
Zabuzard

Reputation: 25903

Use the method WebElement#isDisplayed (documentation) to get the status of an element.

All you need to do is to setup a counter like int counter = 0. Then create a loop over all elements like for (WebElement e : testItems) { ... }. Then, inside the loop, create some sort of if (e.isDisplayed()) { ... }. And inside this you increase the counter like counter++. All in all:

int counter = 0;
for (WebElement e : testItems) {
    if (e.isDisplayed()) {
        counter++;
    }
}

This variant uses the enhanced for-loop. You can of course use other loop variants too.

Using streams this could be made a compact one-liner like

int count = testItems.stream()
    .filter(WebElement::isDisplayed)
    .count();

Note that WebElements can, depending on the website, quickly stale if they aren't processed quickly after their generation. This is indicated by them throwing a StaleElementReferenceException. It happens whenever the website rebuilds itself (completely or partially), your element was then retrieved from an old state of the website and is thus invalid.

If you experience this, you may directly collect the display status of an element before finding the other elements. This decreases the time between generation and access of a single WebElement.

Upvotes: 2

Related Questions