Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to click on hidden element in Selenium WebDriver?

I have a grid which displays some records. When I click on a record and inspect that element it is shown that it is hidden but it is visible in the grid.

My HTML is:

<a href="http://192.168.1.6/eprint_prod_3.8/settings/othercost_add.aspx?type=edit&id=805" title="Plastic Spiral Bind"
<div style="float: left; width: 99%; overflow: hidden; height: 15px; overflow: hidden"> Plastic Spiral Bind </div>
</a>

The above code is hidden while inspecting but it is visible in grid.

Selenium code:

driver.findElement(By.partialLinkText("Plastic Spiral Bind")).click();
like image 915
Santhosh S Avatar asked Mar 01 '14 04:03

Santhosh S


3 Answers

First store that element in object, let's say element and then write following code to click on that hidden element:

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);
like image 82
Alpha Avatar answered Nov 14 '22 23:11

Alpha


You have two approaches. Selenium has been specifically written to NOT allow interaction with hidden elements. The rational is that if a person cannot perform that action, then neither should Selenium. Therefore, to perform the click via Selenium, you must perform the action a user would do to make that button visible (e.g mouse over event, click another element, etc) then perform the click once visible.

However, Selenium does allow you to execute Javascript within the context of an element, so you could write Javascript to perform the click event even if it is hidden.

My preference is to always try and perform the actions to make the button visible

like image 34
Robbie Wareham Avatar answered Nov 15 '22 00:11

Robbie Wareham


Here is the script in Python.

You cannot click on elements in selenium that are hidden. However, you can execute JavaScript to click on the hidden element for you.

element = driver.find_element_by_id(buttonID)
driver.execute_script("$(arguments[0]).click();", element)
like image 5
Peter Avatar answered Nov 15 '22 00:11

Peter