How do I select only visible elements using XPath? How do I select only visible elements using XPath? selenium selenium

How do I select only visible elements using XPath?


This should work:

.//button[.='OK' and not(ancestor::div[contains(@style,'display:none')])and not(ancestor::div[contains(@style,'display: none')])]

EDIT:

The simpler and more efficient expression below:

//div[not(contains(@style,'display:none'))]//button[.='OK']

does not work properly because every button has at least one div that's visible in its ancestors.


Selenium 2 Webdriver gives us the option of the isDisplayed() method which deals with this problem. Nice work by the selenium contributors.


//div[(contains(@style,'display: block'))]//button[@id='buttonid']

This worked for me. Like 'display: none' representing hidden blocks, 'display: block' represents currently displayed block and we can specify any inner tags to be identified as above