XPath for finding an ancestor node containing a CSS class

I am writing several Selenium tests, and I need to find the WebElement ancestor that I already found.

This is what I am trying but returns no results

 // checkbox is also a WebElement WebElement container = checkbox.findElement(By.xpath( "current()/ancestor-or-self::div[contains(@class, 'x-grid-view')]") ); 

The figure below shows the div I selected, highlighted in blue, and the one I want to find with an arrow pointing to it.

enter image description here

UPDATE Tried anticipation 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 Really strange, even by ID not working

 [cucumber]    org.openqa.selenium.NoSuchElementException: Unable to locate element:{"method":"xpath","selector":"./ancestor::div[@id='gridview-1252']"} 

Update 3

Next XPATH works but fragile

 ../../../../../../../* 

+6
source share
1 answer

This should select the desired item.

 ./ancestor::div[contains(concat(' ', @class, ' '), ' x-grid-view ')][1] 

In plain English: from all div ancestor elements that have an ' x-grid-view ' in their class, select the first (closest).

Notes:

  • I combine spaces as a protective measure to prevent partial matches.
  • current() is an XSLT function, not XPath. It does not make sense outside of XSLT. The current node is expressed as . in XPath.
+11
source

Source: https://habr.com/ru/post/912767/


All Articles