Igal
Igal

Reputation: 4783

How to get element's index by xpath?

I've next structure :

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

I was wonder if there is a ways to use XPath, and to write some query were I can get the index of the requested element within the "list" element.

I mean that I'll ask for location of class='column' where the text value is aaa and I'll get 0 or 1...

Thanks

Upvotes: 11

Views: 24821

Answers (4)

Bogdan Molocea
Bogdan Molocea

Reputation: 49

Selenium way to evaluate 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);

Upvotes: 4

Nora
Nora

Reputation: 1482

You can count how many "preceding-siblings" that are also of class 'column', by using this xpath:

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

Upvotes: 0

basilikum
basilikum

Reputation: 10536

You could just count the div elements preceding the element you're looking for:

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

Upvotes: 9

choroba
choroba

Reputation: 242343

You can count the preceding siblings:

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

Upvotes: 5

Related Questions