I'm using IntelliJ IDEA 2020.1 Community Edition for automated testing. The issue seems simple enough. I have a Search drop-down menu which also contains a Search menu option (among other options).
The .java code uses xpath to locate the object, which returns 2 elements:
@FindBy(xpath = "//a[text()='Search']")
WebElement searchButton;
Both objects are found, with the Search button identified as xpath="1" and the Search option as xpath="2"...
To differentiate between the menu button and menu option, I included two Methods, passing in the element and the Index number (0 for the button or 1 for the option):
public void clickOnSearchButton(){
clickIndexedElement(searchButton, 0);
testLogger.log("Clicked on the 'Search' button");
}
public void clickOnSearchOption(){
clickIndexedElement(searchButton, 1);
testLogger.log("Clicked on the 'Search' option");
}
The clickIndexedElement Method also seemed to be quite simple:
public JavascriptExecutor js;
js = (JavascriptExecutor) driver;
public void clickIndexedElement(WebElement elementName, int index) {
testLogger.log("Clicking on Index ["+index+"]");
js.executeScript("arguments["+index+"].click();", elementName);
}
In actuality, clicking on the Search menu button works, but I get an error trying to click on the Search menu option:
LOG: Clicking on Index [0]
LOG: Clicked on the 'Search' button
LOG: Clicking on Index [1]
org.openqa.selenium.JavascriptException: javascript error: Cannot read property 'click' of undefined
(Session info: MicrosoftEdge=87.0.664.75)
Could someone explain in simple terms why the click on Index 0 works but the click on Index 1 doesn't?