Java – XPath for finding ancestor nodes containing CSS classes
I'm writing some selenium tests. I need to be able to find the ancestors of the webelement I've found
This is what I'm trying, but it doesn't return any results
// check@R_339_2419@ is also a WebElement WebElement container = check@R_339_2419@.findElement(By.xpath( "current()/ancestor-or-self::div[contains(@class,'x-grid-view')]") );
The image below shows the dark blue highlighted div I selected and the one I want to point to with an arrow
Update tried prestomanifesto's suggestion and got the following error
[cucumber] org.openqa.selenium.InvalidSelectorException: The given selector ./ancestor::div[contains(@class,'x-grid-view']) is either invalid or does not result in a WebElement. The following error occurred: [cucumber] [InvalidSelectorError] Unable to locate an element with the xpath expression ./ancestor::div[contains(@class,'x-grid-view']) because of the following error: [cucumber] [Exception... "The expression is not a legal expression." code: "51" nsresult: "0x805b0033 (NS_ERROR_DOM_INVALID_EXPRESSION_ERR)" location: "file:///C:/Users/JUAN~1.MEN/AppData/Local/Temp/anonymous849245187842385828webdriver-profile/extensions/fxdriv
Update 2 is really strange, not even ID
[cucumber] org.openqa.selenium.NoSuchElementException: Unable to locate element:{"method":"xpath","selector":"./ancestor::div[@id='gridview-1252']"}
Update 3
The following XPath is effective but fragile
../../../../../../../*
Solution
This should select the element you want
./ancestor::div[contains(concat(' ',@class,' '),' x-grid-view ')][1]
In simple English: choose the first (closest) element among all ancestor div elements with 'x-grid-view' in their class
Notes:
>I use space as a defensive measure to prevent partial matching. > Current () is an XSLT function, not an XPath function It has no meaning beyond XSLT The current node is represented as In XPath