The click on a WebElement action

We have seen how to click a WebElement by calculating the offset to it. This process may not be needed every time, especially when the WebElement has its own identifiers, such as a name or an ID. We can use another overloaded version of the click() method to click directly on the WebElement.

The API syntax for clicking on a WebElement is as follows:

public Actions click(WebElement onElement)

The input parameter for this method is an instance of the WebElement on which the click action should be performed. This method, like all the other methods in the Actions class, will return an Actions instance.

Now let's try to modify the previous code example to use the click(WebElement) method, instead of using the moveByOffset() method, to move to the location of the WebElement and click on it using the click() method:

@Test
public void shouldClickOnElement() {

driver.get("http://guidebook.seleniumacademy.com/Selectable.html");

WebElement one = driver.findElement(By.name("one"));
WebElement eleven = driver.findElement(By.name("eleven"));
WebElement five = driver.findElement(By.name("five"));
Actions actions = new Actions(driver);

//Click on One
actions.click(one);
actions.build().perform();

// Click on Eleven
actions.click(eleven);
actions.build().perform();

//Click on Five
actions.click(five);
actions.build().perform();
}

Now the moveByOffset() method has been replaced by the click(WebElement) method, and, all of a sudden, the complex coordinate geometry has been removed from the code. If you're a tester, this is one more good reason to push your developers to provide identifiers for the WebElements.

If you observe the previous examples for the moveByOffset and click methods, all the operations of moving the mouse and clicking on tiles 1, 11, and 5 are built separately and performed separately. This is not how we use our Actions class. You can actually build all these actions together and then perform them. So, the preceding code will turn out to be as follows:

    @Test
public void shouldClickOnElement() {

driver.get("http://guidebook.seleniumacademy.com/Selectable.html");

WebElement one = driver.findElement(By.name("one"));
WebElement eleven = driver.findElement(By.name("eleven"));
WebElement five = driver.findElement(By.name("five"));
Actions actions = new Actions(driver);

actions.click(one)
.click(eleven)
.click(five)
.build().perform();
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.53.5