How to get the index of an element by xpath?

I have the following structure:

<div id='list'> <div class='column'>aaa</div> <div class='column'>bbb</div> ... <div class='column'>jjj</div> </div> 

I was wondering if there are ways to use XPath and write some query: I can get the index of the requested item in the list element.

I want to say that I will request the location class='column' , where the text value is aaa , and I will get 0 or 1 ...

thanks

+6
source share
4 answers

You can simply count the div elements preceding the element you are looking for:

 count(div[@id = 'list']/div[@id = 'myid']/preceding-sibling::div) 
+5
source

Selenium to assess the position:

  int position = driver.findElements (By.xpath ("// div [@ class = 'column' and text () = 'jjj'] / preceding-sibling :: div [@ class = 'column']")). size () + 1;
 System.out.println (position);
+3
source

You can count previous siblings:

 count(//div[@id="list"]/div[@id="3"]/preceding-sibling::*) 
+2
source

You can calculate how many “previous siblings” that also refer to the “column” of the class using this xpath:

 //div[@class='column' and text()='jjj']/preceding-sibling::div[@class='column'] 
0
source

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


All Articles