I'm trying to create a general method to find a WebElement by its "label" (e.g. the text displayed in a button) and returning the WebElement:
//Find Webelement by Label
protected WebElement getWebElementByLabel(String strCSSselector, String strTargetLabel) {
//Create list with all elements via CSSselector
List<WebElement> elementList = driver.findElements(By.cssSelector(strCSSselector));
//Create return element
WebElement returnElement;
//Identify the via its label
for (WebElement element : elementList) {
//Read label from element
String strElementLabel = element.getText();
//Set return value if target label found
if (strElementLabel.equals(strTargetLabel)) {
returnElement = element;
}
}
//Return webelement
return returnElement;
}
However, I get the error 'The local variable returnElement may not have been initialized'. Any ideas on how to resolve this are appreciated. If possible I would prefer to return the value from within the for-loop (if this is not possible a hint on the "why" would be appreciated).
Note: For now I'm ignoring the case that multiple elements might have the same name