When retrieving an html table WebElement list such as the following (e.g. by tag):
webDriver.findElement(By.id("mainTable"))
.findElements(By.tag("tr"))
Is there a guaranteed order for returned list? Can I safely assume element[i] comes before element[i+1] in the table rows order?
I've looked into the official docs, and googled around, but no luck.
Yes, there is a guaranteed order for returned list and you can safely assume element[i] comes before element[i+1] in the table rows order.
You can refer the implementation of findElements() method in RemoteWebDriver and By class with different parameters. What you need is the below code for findElements method, which takes two string as parameters.
protected List<WebElement> findElements(String by, String using) {
if (using == null) {
throw new IllegalArgumentException("Cannot find elements when the selector is null.");
}
Response response = execute(DriverCommand.FIND_ELEMENTS,
ImmutableMap.of("using", by, "value", using));
Object value = response.getValue();
List<WebElement> allElements;
try {
allElements = (List<WebElement>) value;
} catch (ClassCastException ex) {
throw new WebDriverException("Returned value cannot be converted to List<WebElement>: " + value, ex);
}
for (WebElement element : allElements) {
setFoundBy(this, element, by, using);
}
return allElements;
}
Notice that the method uses ImmutableMap to return the web elements found and add them to a list.
An immutable, hash-based Map with reliable user-specified iteration order.
Since, ImmutableMap retains the iteration order, you can safely assume the WebElement list return by findElements method is ordered.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With