Selenium WebDriver – How to click on a hidden link or Menu

I have come across an issue today about handling hidden elements. And I came up with the below questions to be answered:

  • How to click on a hidden link in WebDriver?
  • How to click on a hidden element in WebDriver?
  • How to click on a SubMenu which is only visible after hovering the mover over to Menu?

Environment:
OS : Windows 7 / Browser: IE9 and FF10 / Web Driver : Selenium 2.19.0

Issue:

In Selenium WebDriver, I found one issue that was about the link in the Sub Menu that I wanted to do check and then click. Now, The main Menu was fixed on the page so that I could click on that element and got the text and confirmed. However, while trying to get the value for a SubMenu, I failed. It did not find those element and I found that there is the problem.

Solution:

WebDriver actually emulates user actions so it will only be able to do those things that a user is able to do. In the webpage that I was testing, it uses a JavaScript to load the Menu and then while hovering my mouse over to that Menu Text it loaded the SubMenu. So that means to say, at page load the SubMenu was hidden.

Now, to get a work around this issue, I had to first move my mouse towards the main Menu (or click on it) to be able to display the SubMenu. There is not simple and straight answer to this issues. And ofcourse, then I googled it. I finally got to the answer of using Actions in the code. Here is the code if you want to have a look at it.

WebElement mnuElement;
WebElement submnuElement;
mnEle = driver.findElement(By.Id("mnEle")).Click();
sbEle = driver.findElement(By.Id("sbEle")).Click();

Actions builder = new Actions(driver);
// Move cursor to the Main Menu Element
builder.MoveToElement(mnEle).Perform();
// Giving 5 Secs for submenu to be displayed
Thread.sleep(5000L);
// Clicking on the Hidden SubMenu
driver.findElement(By.Id("sbEle")).Click();

The only problem with this code is it works like a charm with FF but doesn’t work with IE. In IE, mouse cursor does not stay on element and as a result popup becomes visible for a fraction of a second or doesn’t appear.

You can also use JQuery as another work around to this hence it will execute it and move the pointer as you need.
Using the .mouseover() method

js.ExecuteScript("return $(\"a:contains('Fruits')\").mouseover();"); // Mouse hove to main menu
webDriver.FindElement(By.LinkText("Banana")).Click();

 

OR using the .hover() method

((JavascriptExecutor)driver).executeScript("$('div#Fruits').hover();");
webDriver.FindElement(By.LinkText("Banana")).Click();

 

OR using the .mouseenter() method

((JavascriptExecutor)driver).executeScript("$('div#Fruits').mouseenter();")
webDriver.FindElement(By.LinkText("Banana")).Click();

 

Give this a go and please let me know which one helped you resolve your issue. :)

Comments

  1. ami says:

    it was very helpful for me. thank you very much.
    I had the same problem but i resolve it by using your first solution

  2. Anit Patel admin says:

    You are welcome ! Thanks for visiting the blog !

    • Lakshay says:

      Hi Anit,

      First code worked fine for me, but I don’t understand the logic.
      It worked for the below code:-
      mnEle = driver.findElement(By.Id(“mnEle”)) //removed .Click();
      sbEle = driver.findElement(By.Id(“sbEle”)) //removed .Click();
      makes sense i think, but the submenu displays only after mouse over on main menu, so ideally the above code should give error on the second statement itself:-
      sbEle = driver.findElement(By.Id(“sbEle”))
      because by this time selenium should not be able to find the sub menu element, as mouse over is not yet performed. please explain me why it worked.

      Regards,
      Lakshay

    • Bhakti Shah says:

      Hello!

      Hoe can we we print a button’s onclick attribute??
      Any idea??
      plz respond soon..

  3. Bill Bachelder says:

    I am new to Selenium, and have a new for similar code as described above. My only issue in understand the code is the object js in the mouseover example. How was that instantiated?

    Bill Bachelder

  4. Anit Patel admin says:

    I think that is automatically bundled with the WebDriver jar files so you can just directly use it when required.

  5. hari says:

    Hi Anil,
    I am trying over your scripts, facing some problem which is

    I have used your below scripts
    ((JavascriptExecutor)driver).executeScript(“$(‘div#Fruits’).hover();”);
    webDriver.FindElement(By.LinkText(“Banana”)).Click();

    the type webDriver shows error “webDriver cannot be resolved”
    What could be the solution, can you please help me out in this

    Thanks in Advance
    Hariprasad

    • Anit Patel admin says:

      Hi Hariprasad,

      Just wanted to know if you have initialised the object webDriver in your script ?
      Please double check that if you haven’t done that.

      If still doesn’t work then try other possible solutions that I have mentioned.
      I hope this will be helpful.

      • gaurav kumar says:

        Hi Anil,
        this code is for java.But what is the code for c#.Could you share as that would be really helpful.

        Thanks in advance.
        Gaurav kumar

        • Anit Patel Anit Patel says:

          Hi Gaurav,

          I have not tried the code for C# yet but I am sure you can find some tools to convert the code from one language to another.
          May be try to do the same operation in Selenium IDE ( if possible) and then export the code to your desired language.
          That is how I suggest beginners to learn which is simple and easy way and later they pick up the speed after some experience.

          I hope this will be helpful to you…

          Cheers,
          Anit

  6. Amol says:

    Hi Anil,

    I am having an issue selecting an option from dropdown.
    The problem I am facing is as below:
    1. To make the dropdown visible, I have to click on a link.
    2. On clicking the link, the dropdown becomes visible, but it disappears within seconds, due to which my code fails giving “Element not visible error.

    Following is the code I am using:
    d.findElement(By.xpath(SelectStateDropDown)).click(); // To make the dropdown visible
    WebElement country = d.findElement(By.xpath(xPath));
    List options = country.findElements(By.tagName(tag));

    for (WebElement option : options) {
    String Value = option.getAttribute(attr);
    boolean result1 = selectOption.contains(Value);
    if(result1)
    {
    option.click();
    break;
    }

    }
    }

    Please suggest.

  7. Jirka bianco Vágner says:

    Man, you saved my life! :) Thanks a lot for sharing your knowledge. Greetings from Czech Republic! ;)

  8. sagar says:

    I need to click on a element(login), which appears if i scroll the mouse over the main menu(sign in) but selenium fails to identify the object log in, which i believe disappears since mouse is not moving over, how can i handle this, please help me…

  9. Paras Vora says:

    In my case, i can have xpath or the id of an element, how can i make the mouseover element?

  10. Paras Vora says:

    In my case, i can have xpath or the id of an element, how can i make the mouseover event over that element?

    • Anit Patel Anit Patel says:

      Paras,
      I think both ID ad XPaths are sufficient to do it.
      See the code in the blog which will help you solve your query.
      Just need to replace the IDs of Menu to your script Menu Ids.
      I hope that will solve the issue.

      Cheers,
      Anit

      • Paras Vora says:

        Thanx for that quick reply.
        If, i want to use this:
        ((JavascriptExecutor)driver).executeScript(“$(‘div#Fruits’).hover();”);
        webDriver.FindElement(By.LinkText(“Banana”)).Click();
        I have the xpath of the element on which, the mouseover element has to be fired then, how should i alter my code?
        what should be the selecter in this ?
        $(‘div#Fruits’).hover();

  11. madhu says:

    this code was very much useful
    thanks

  12. amit says:

    Thanks…….. code is working fine

  13. Dani says:

    Hi Anit,

    I need you help, I am facing same problem for on mouse over pop up. I am working on application which has JQuery Pop up on mouse over and that pop up has links to click. Selenium RC is able to click on link but pop up is not visible on screen.

    I want to verify JQuery pop up and tool tips on mouseover functionality. I would appreciate if you could let me know if Selenium RC works with JQuery Pop up or any other workaround.

    Thanks,
    Dani

    • Anit Patel Anit Patel says:

      Hi Dani,

      I think that was possible with Web Driver only but I have not really got a chance to test it with RC.
      Please try to find an alternative source to get a solution if this code din’t work out for me.
      I will try and look at it when I am a bit freed up and will let you know then…

      Cheers.

      • Dani says:

        Hey Anit,

        Thanks for your reply.

        What do you suggest to use Selenium RC or Web Driver for scripting application?

        Thanks
        Dani,

        • Anit Patel Anit Patel says:

          Hi Dani,
          It would be a wise decision if you use Web Driver which will be more beneficial to you at later stage.
          I hope that helps.

          -Anit

  14. Rakesh Jain says:

    Hi Anit,
    I am trying to click on a option from “Fixture” menu in Cricinfo.com. I am able to make menu visible but not able to click on option.
    Code:
    WebDriver driver = new FirefoxDriver();
    driver.get(“http:cricinfo.com”);
    ((JavascriptExecutor) driver).executeScript(“mopen(‘m3′)”);
    Thread.sleep(5000L);

    driver.findElement(By.xpath(“//*[@id='mgDdRht']/tbody/tr[3]/td/a”)).click();
    Can you please help me out on this.

    Thanks!
    Rakesh Jain

  15. Dinesh says:

    Hi Anit,
    I see this blog really useful. Good work!
    Now, my question is when I convert the ‘clickAt’ function from HTML to JUnit Webdriver code, I get the following message,
    // ERROR: Caught exception [ERROR: Unsupported command [clickAt]]
    Please let me know if there is a way to solve this.

    -Dinesh

  16. Arun C says:

    Many Thanks mate, Using the .mouseover() method was very useful …

    It solved our issue that was pending more than a week +

    And do you know any book for Selenium 2 advanced?

    Arun C – Chennai

  17. Arun C says:

    I have a query also;

    From the example you’ve shown ;

    js.ExecuteScript(“return $(\”a:contains(‘Fruits’)\”).mouseover();”); // Mouse hove to main menu
    webDriver.FindElement(By.LinkText(“Banana”)).Click();

    If I have an xpath like //*[id='text1] .. how will I give this in the js.ExecuteScript ?

  18. kiran says:

    hi Anit ,
    i am using
    Windows 7 ,
    IE driver 2.21
    i am trying to click on a div and perform some action .but when i run my program it returns true on click but does not perform any action. i have checked and Xpath is correct.
    i have used
    driver.FindElement(By.XPath(arrControls[cnt])).Click();
    also
    selenium.KeyPress(arrControls[cnt], “\\13″);
    both are not working. Could you please help me

  19. Brian R. says:

    Thanks! Very Helpful!

  20. Neils says:

    How we set in web site to click on Image & than we show dialog box OR PopUp.which is show msg????

  21. Kishan Kumar says:

    Hi Anit,

    Thanks a lot for the solution. It really helped solve one of the issues we were facing.

    Kishan Kumar

  22. Karen says:

    Your first solution worked for me – thank you. Saved me a significant amount of time.

  23. priyanka says:

    Hello Admin,
    I have following java code:
    ———————————————-
    public void userManagement() throws InterruptedException
    {
    System.out.println(“in userManagement 1″);
    Actions builder = new Actions(driver);
    //Mouseover Administartion
    builder.moveToElement(administrationMenu).perform();
    System.out.println(“in userManagement 1/1″);
    WebDriverWait wait = new WebDriverWait(driver, 5);
    // Click on User Management
    WebElement menuItem = wait.until(ExpectedConditions
    .visibilityOf(Administration));
    //Mouseover Administartion sublevel
    builder.moveToElement(Administration).perform();
    System.out.println(“in userManagement 1/2″);
    menuItem = wait.until(ExpectedConditions.visibilityOf(userManagement));
    System.out.println(“in userManagement 1/3″);
    //click on user management

    System.out.println( userManagement.getText());
    if(“User Management”.equals(userManagement.getText()) ){
    System.out.println( userManagement.getText());
    builder.moveToElement(userManagement).click(Administration);
    System.out.println( userManagement.getText());
    }
    else{
    System.out.println(“Element not found”);
    return;
    }
    System.out.println(“in userManagement 1/4″);
    Thread.sleep(30000);
    System.out.println(“in userManagement 2″);
    ——————————–
    I have 3 levels to mouseover in this code and finally click on 3rd level element.
    In this code some times i get error and some times it runs successfully without error and I can not find out why?
    Also when it shows no error it fails to move to new screen by clicking [Administrator (Main menu) --> Administrator (Sub menu) -- > User Management(Sub Sub menu)]

  24. Annonymous says:

    Guys,

    While fighting with the same problem I found a very good solution on Internet
    (http://code.google.com/p/selenium/issues/detail?id=2067)

    String mouseOverScript =
    // all browsers except IE before version 9
    “if(document.createEvent) {” +
    “var evObj = document.createEvent(‘MouseEvents’);” +
    “evObj.initEvent(‘mouseover’, true, false); ” +
    “arguments[0].dispatchEvent(evObj);” +
    “} ” +
    // IE before version 9
    “else if(document.createEventObject) ” +
    “{ arguments[0].fireEvent(‘onmouseover’); }”;
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript(mouseOverScript, element);

    I hope you’ll find it useful.

  25. Dhanaprakash says:

    Hi Anit,
    I want to perform mouseover on one element named “track order”. Only one attribute(title) is available for this element but not able to do anything with this.
    The JQuery looks like this for this element
    $(‘#track_order’).hover(function(){
    $(‘.tc-box’).hide(); //Make all leaf hide at Start
    var targetHeight = $(“> .tc-box”, this).outerHeight(true);
    var leftPos = $(this).position().left – 85 +’px’;
    var topPos = $(this).position().top + 16 +’px’;

    $(‘> a’, this).css({“background-image”:”url(‘../images/drop_arrow.png’)”})
    $(“> .tc-box”, this).css({‘top’:topPos,’left’:leftPos}).show();
    }
    I Tried the below solution which u already provided.

    ((JavascriptExecutor)driver).executeScript(“$(‘#track_order’).hover();”); . But still no use ..

    Can you pls help me on this .. ?

    How do i call this in Selenium Webdriver ?

    Thanks
    V J Dhanaprakash

  26. shaama says:

    Hi Anit/ All,

    I have automated our login page, which has an uname and pwd feilds, and a multiple profile drop down and a multiple contracts drop down. SO some users have multiple profile drop down and a multiple contracts drop down, some only multiple profile drop down and some only uname and pwd.

    So now i have to check if multiple profile drop down is present, if present then only pass the values or directly click on submit button.

    How to handle this??????

    I have used isDisplayed() , also tried —
    Dimension multi_prof_dd = driver.findElement(By.xpath(“//*[@id='ddlCustomerList']“)).getSize();
    if(multi_prof_dd!= null)
    {
    // pass val
    //click on submit
    }
    //click on submit button

    Plz help me .. Its urgent.

    Thanks in Advance.

  27. Shilpa says:

    Hi Anit,
    How do you identify which tab is selected in a brower using Selenium?

  28. Savan Patel says:

    Hi Anit,

    I am unable to create object for Actions class even i have imported jar file and package
    when i am trying to create object “Actions builder = new Actions(GlobalVariable.oDriver);”
    Automatically cursor is coming out of method stopTranslators();
    .
    my code is
    public void stopTranslators() {
    try
    {
    GlobalVariable.oDriver.findElement(By.xpath(“/html/body/form/div[2]/table/tbody/tr/td/div/div/div/div/span[2]/span/span”)).click();
    Thread.sleep(10000);
    GlobalVariable.oDriver.findElement(By.name(“ulMain$tmpl1$ctl00$translatorsGrid$Header0$chkAll”)).click();

    GlobalVariable.oElement =GlobalVariable.oDriver.findElement(By.xpath(“/html/body/form/div[2]/div/table[2]/tbody/tr/td/div/div/ul/li/a/span”));
    Actions builder = new Actions(GlobalVariable.oDriver);
    // Move cursor to the Main Menu Element
    builder.moveToElement(GlobalVariable.oElement).perform();
    // Giving 5 Secs for submenu to be displayed
    Thread.sleep(5000L);
    // Clicking on the Hidden SubMenu

    }

  29. Girish V says:

    Hi Anil,

    I am new to web driver. I was using Selenium RC.
    In web driver i needs to implement below equivalent code in web driver.
    $sel ->click(“logid”);
    $sel->wait_for_text_present(“open”, 10000);

    Description : After clicking logid button i needs wait for text open to be present on UI

  30. Vijay says:

    Hi ,

    I am new to selenium and got a toughest task. till now I was working with selenium in adding the values to fields and working with radio buttons. Now they have asked me to work on ribbons that looks like Microsoft office. I need to work with menus and sub menus.how to achieve this. is there any plugins available?

  31. Vijay says:

    Hi ,

    This is for Selenium RC

    I am new to selenium and got a toughest task. till now I was working with selenium in adding the values to fields and working with radio buttons. Now they have asked me to work on ribbons that looks like Microsoft office. I need to work with menus and sub menus.how to achieve this. is there any plugins available?

  32. sarika says:

    Hi Anit,
    How can I verify invisible objects which gets enabled only on incorrect data entry (label before textbox eg: login scenario) using xpath in selenium webdriver.
    If all labels display with error message (e.g. username label and password label),I am able to verify and capture text (error messages).
    But if I enter correct Username,Webdriver continue searching for that Xpath(username label) and does not respond.
    Can you please help me ?

    -Regards

  33. sheela says:

    I am having my page source code like

    By clicking the link in the source code..its going the source code of the particular section in my page.If I want to access the elements presen in the link..what i have to do? I am using java with selenium webdriver

  34. divya says:

    Hi Anit,
    I have one problem in selenium. how to click a link (flow is for eg i need to click a link subvisit for that we need to Click trasanction link Actual flow is Transaction–> Diagnotech–> Subvist ) first i need to click transaction button in that i need to click Diagnotech in that i need to click subvist. how can we write for this.

    Can you please help me?

  35. Loya says:

    Hi Everybody,
    Thanks all of you for the information, But there is still some problem from my side for the similar issue here, Kindly please anybody help me fix it:

    Description:

    I would like to click the hide link “Partstore Activity” from the Menu “RESOUCES”, the Menu “RESOUCES” can be clicked, but once you click it, it navigates to different page, so the manual functionality is: Mouse over the Menu “RESOUCESE” -> Click the sub-link “Partstore Activity”, That is what I want, here is the HTML for the “RESOUCES” Menu and the sub-link of “Partstore Activity”:

    RESOURCES 



    PartStore Activity



    Also I would like to attached the screenshot, I was failed with the following ways which I have tried:

    1. Click the sub-link directly by using findBy Xpath and LinkText
    2. I have tried to using action to simulate the mouse over then click the sub-link
    new Actions(TestCaseBase.threadDriver.get()).moveToElement(desiredMenu);
    Actions action = new Actions(TestCaseBase.threadDriver.get());
    action.moveToElement(desiredMenu);
    action.perform();
    sub-Link.click

    All the ways I tried failed by the same error:

    org.openqa.selenium.interactions.MoveTargetOutOfBoundsException: Element cannot be scrolled into view:https://partsmc.rd.cat.com/partstoreweb/jsp/logon.jsp#

    Could anyone please help me how to fix this issue?

  36. Loya says:

    Hi Anit, Glad to talk with you here,
    As some problem to attach the HTML and also screenshot,
    so i have sent a mail to your account: anit.patel7@yahoo.com, Could you please help me check and look at my problem about the hide link in Selenium, Thank you so much

  37. Mahesh says:

    Hi Anil,

    I have just started using selenium IDE2.0 and wanted to know if its possible to simulate the clicking of submenu in IDE instead of webdriver? If so, how?

  38. Galina says:

    Thank you very much! it was very helpful for me!
    I had the same problem and i resolve it by using your first solution.

  39. Raghu says:

    Hi,
    How to click all links in an application,It includes both visible and invisible links.
    Please help me.
    Thanks

  40. Paul says:

    This is my first time leaving a comment on a Test automation blog.
    Thank you very much! it was very helpful for me!

  41. Raghu says:

    Hi,
    I am new to selenium web driver,Facing some problems,please help me.
    Am trying to automate the Google search button properties,created two classes in two different package
    one is properties class and main class,actually am calling properties class in main class.
    HERE IS CODE…
    /*properties class*/
    package com.property;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;

    public class Gbuttonproperty {
    private WebDriver driver;
    private String buttonText;
    private int buttonhight;
    public String buttontext(String locator,String Value)
    {
    if(locator==”xpath”)
    {
    System.out.println(“xpath is=”+Value);
    buttonText=driver.findElement(By.xpath(Value)).getText();
    return buttonText;
    }
    else if(locator==”id”)
    {
    System.out.println(Value);
    buttonText = this.driver.findElement(By.id(Value)).getText();
    return buttonText;

    }
    else if(locator==”name”){
    buttonText = this.driver.findElement(By.name(Value)).getText();
    return buttonText;
    }
    else if(locator==”classname”){
    buttonText = this.driver.findElement(By.className(Value)).getText();
    return buttonText;
    }
    else if(locator==”cssSelector”){
    buttonText =this.driver.findElement(By.cssSelector(Value)).getText();
    return buttonText;
    }

    return null;
    }
    public int buttonhight(String locator,String Value){

    if(locator== “xpath”)
    {
    buttonhight = driver.findElement(By.xpath(Value)).getSize().getHeight();
    return buttonhight;
    }
    else if(locator == “id”)
    {
    buttonhight =this.driver.findElement(By.id(Value)).getSize().height;
    return buttonhight;
    }
    else if(locator==”name”){
    buttonhight = this.driver.findElement(By.name(Value)).getSize().getHeight();
    return buttonhight;
    }
    else if(locator==”classname”){
    buttonhight = this.driver.findElement(By.className(Value)).getSize().getHeight();
    return buttonhight;
    }
    else if(locator==”cssSelector”){
    buttonhight = this.driver.findElement(By.cssSelector(Value)).getSize().getHeight();
    return buttonhight;
    }
    return 0;
    }

    }

    /*MAIN CLASS*/
    package com.properies;
    import com.property.Gbuttonproperty;

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.testng.annotations.AfterMethod;
    import org.testng.annotations.BeforeClass;
    import org.testng.annotations.BeforeMethod;
    import org.testng.annotations.Test;

    public class Gbutton {
    private WebDriver driver;
    private String baseUrl;
    Gbuttonproperty b = new Gbuttonproperty();

    @BeforeMethod
    public void start() throws Exception {
    baseUrl = “https://www.google.com/”;
    driver = new FirefoxDriver();
    }
    @Test
    public void button(){
    driver.get(baseUrl );
    Gbuttonproperty b=new Gbuttonproperty();
    b.buttontext(“xpath”, “//*[@id='gbqfba']“);

    }
    @AfterMethod
    public void tearDown() throws Exception {
    driver.quit();
    }

    }

  42. Pooja says:

    Hi Anit,
    Thanks for writing this. All these solutions used to work for me as well, but I dn’t know for what reason they have stopped working now. I have FF22 and selenium 30.
    I googled and found that it is existing issue with some browsers, “https://code.google.com/p/selenium/issues/detail?id=4893″
    But I still didn’t get any alternative solution. My Web is having many mouse hover events so kindly please help me figure out what can be done to simulate mouse hover on anchor tag.
    Here is sample of my UI

    Main Menu

    subMenu1

    SubMenu2

  43. jagadishwar says:

    Hi,
    I have a query that i want to check the negative scenario.condition should be true if the expected link button not present in the application and should not skip the remaining test scripts

    Advance Thanks

  44. Mark Heilman says:

    Did anyone ever find a solution to IE???

    As pointed out, things work in Chrome / FF but IE… oh what a pain…

    Does using the JS work as a work around for IE 8/9??? doing things in Python, but can execute JS not an issue.

    Any feedback appreciated.

    Best
    Mark Heilman
    Billings, MT, USA

  45. jyothi says:

    Hi Anit,

    can u just help me out how to read a data from word file using selenium…

Speak Your Mind

*