0

I am very much displaying my ignorance here, but when a page has multiple elements with the same class name it seems like my code no longer interacts with the page in a predictable way. For example, if there is a single element on a page with class "submit" I can write:

WebElement submitButton;
submitButton = bot.findElement(By.className("submit"));
submitButton.click();

And that submit button will be clicked in the browser. But, if on that same webpage there are two (or more) elements with class "home", I could write:

WebElement homeButton;
homeButton = bot.findElement(By.className("home"));
homeButton.click();

And it seems nothing is clicked on.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Euch
  • 113
  • 3
  • probably returns and array of elements with that class. have you tried console logging what it returns to see? – HolyMoly Jun 20 '18 at 20:55
  • There might be elements with class home located in the DOM and being hidden. You script tries to click them but nothing would happen in that case. – sen4ik Jun 20 '18 at 22:19

1 Answers1

0

Just like findElement(By.id(java.lang.String id)) or findElement(By.name(java.lang.String name)), findElement(By.className(java.lang.String className)) would also return you the first matching element on the Web Page.

By.className("submit")

As you mentioned that there is a single element present in the HTML DOM with class submit, hence your Locator Strategy will always find the unique element and your subsequent click() would work well.

By.className("home")

As you mentioned that there are two (or more) elements with class home in the HTML DOM, so the Locator Strategy within the line bot.findElement(By.className("home")); will pickup the first matching element present in the DOM Tree irrespective of the conditions if the element is visible, displayed, intercatable or not. Hence your subsequent click() may even fail.

Impact

In such cases you may be facing either of the following exceptions:

Solution

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352