How to Move to Element and Click in Selenium

Move to Element and Click in Selenium | Move To Element is a kind of action on the web page in which the mouse cursor moves to a WebElement.

To move the mouse cursor to a WebElement, we use the moveToElement() method of actions class in Selenium WebDriver. The API syntax for moveToElement() method is as follows:

public Actions moveToElement(WebElement toElement)

This method takes target WebElement as an input parameter on which the mouse should be moved.

Let’s understand moveToElement action by taking a scenario.

Scenario to Automate:

1. Launch the Firefox browser.
2. Open URL “https://selenium08.blogspot.com/2020/01/click-and-hold.html”.
3. Locate WebElements titleA and titleC by By.xpath.
4. Move the mouse cursor at the place of titleA.
5. Click and hold titleA.
6. Release titleA at the place of titleC.

Follow all the important steps in the below program code to automate the above scenario.

Program code 1:

package moveToElementAction; 
import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.openqa.selenium.interactions.Actions; 

public class MoveToElement { 
public static void main(String[] args) 
{ 
// Create an instance of Firefox driver class to launch web browser.
   WebDriver driver = new FirefoxDriver(); 
   driver.manage().window().maximize(); 
 
   String url = "https://selenium08.blogspot.com/2020/01/click-and-hold.html"; 
   driver.get(url); 

// Locate the element A by By.xpath. 
   WebElement titleA = driver.findElement(By.xpath("//li[text()= 'A']")); 
   WebElement titleC = driver.findElement(By.xpath("//li[text()= 'C']")); 

// Create an object of actions class and pass reference of WebDriver as a parameter to its constructor. 
   Actions actions = new Actions(driver); 

// Call moveToElement() method of actions class to move mouse cursor to a WebElement A. 
   actions.moveToElement(titleA); 
   actions.clickAndHold(); 
   
   actions.moveToElement(titleC); 
   actions.release().perform(); 
  } 
}

In this example code, we have moved to titleA, clicked and held it, and then moved titleA to the location of titleC by using the moveToElement() method of actions class.

Here, release() method of actions class has been used to drop element titleA from the mouse at the location of titleC. The release() method releases the left mouse button on the WebElement.


In this tutorial, we have covered almost all important points related to how to move to element and click in Selenium WebDriver. Hope that you will have understood the basic concept of moving to element and clicking in Selenium. In the next, we will learn how to perform drag and drop action in Selenium with the help of practical scenario.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love