0

I have an XPath:

$x(("//div[@class='ag-header-row']"))[1]

that gives me an array of divs. The [1] at the end is necessary because there are other rows with this class.

I know about [last()] but not sure where to insert it.

How do I modify the XPath to select the last div?

Here is screenshot of the elementsenter image description here

kjhughes
  • 106,133
  • 27
  • 181
  • 240
Steven Greenbaum
  • 311
  • 4
  • 17
  • Try `("//div[@class='ag-header-row']")[count("//div[@class='ag-header-row']")]` – JaSON Aug 28 '20 at 12:53
  • Thanks for responding @JaSON I tried that in Google console but got "count is not defined" error. I was hoping to use [last()] because I also want to use [first()] – Steven Greenbaum Aug 28 '20 at 13:06
  • There is no such operator in XPath as `first`. Try `"(//div[@class='ag-header-row'])[last()]"` – JaSON Aug 28 '20 at 13:12
  • If you look at my path that works and returns an array of divs there is a [1] at the end. That [1] is necessary to get the array. Your suggestion doesn't work because it doesn't have the [1]. I am not sure how to add [last()] – Steven Greenbaum Aug 28 '20 at 13:29
  • Your `[1]` doesn't looks like a part of XPath. I suggested you an XPath-solution. Share more details about your problem - it might be related to programming language – JaSON Aug 28 '20 at 13:57
  • 1
    @JaSON: Right, as I already [mentioned in my answer below](https://stackoverflow.com/a/63635203/290085), the `[1]` is being applied in the context of JavaScript (in a browser console), not XPath. – kjhughes Aug 28 '20 at 14:00

2 Answers2

1

Your invocation of an XPath expression,

$x(("//div[@class='ag-header-row']"))[1]

means to select all div element with the given class attribute value, and, in JavaScript, outside of XPath take the second one (because JavaScript arrays start at 0, not 1 like XPath's).

You cannot replace the [1] with [last()] because there last() is an XPath function, not a JavaScript function.

If you want the last such div move [last()] into the XPath:

$x("(//div[@class='ag-header-row'])[last()]")

See also:

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • The [1] is necessary to select the correct row. The row I am interested in is the 2nd row of that class. I then want the last element in that row – Steven Greenbaum Aug 28 '20 at 14:51
  • Create a [mcve] using a simplified example of HTML or XML ***as text, never as an image*** to convey your requirements -- your prose description is quite unclear. – kjhughes Aug 28 '20 at 16:30
0

I was able to solve by incorporating reference to parent element

$x("//div[@class='ag-header-container']//div[@class='ag-header-row']/div[last()]")
Steven Greenbaum
  • 311
  • 4
  • 17