I have more than 1 XPath pointing to a web element and I want to determine if both elements are equivalent (i.e, if I perform the action sendKeys() or click() on both web elements the action would be executed on the same web element) Currently I'm checking for equality using the following method:
WebElement element1 = driver.findElement(By.xpath(".//*[@id='ap_email']"));
WebElement element2 = driver.findElement(By.xpath(".//*[@type='email']"));
However, I am unsure how the method determines equality?
The driver generates a reference for each encountered
HTMLElement object in the document and always returns the same reference for an
This reference is stored in the
WebElement.id property on the client side and has nothing to do with the id attribute used with a locator.
So to determine the equality between two
WebElement, the client simply tests the reference stored in
And are there any circumstances where the two web elements are in fact the same but the method shows they are different?
Technically speaking, no it never happens and it would be a serious issue if it was the case.
But it kind of depends on what you mean by the same. For instance a button can look the same at two different moments, but may have been replaced by an identical one which would generate a new reference. This is the case when the page or some parts are reloaded:
driver.get("http://stackoverflow.com/"); WebElement elementA = driver.findElement(By.cssSelector("#logo")); WebElement elementB = driver.findElement(By.cssSelector("#logo")); boolean same1 = elementA.equals(elementB); // return true elementB.click(); // reloads the page, all the previous web element are now obsolete WebElement elementC = driver.findElement(By.cssSelector("#logo")); boolean same2 = elementA.Equals(elementC); // return false