Reputation: 7486
Is there a way to get the index of the matched element f.e. let say I have a table and use the following xpath expression to find element by content :
//table/thead/tr/th[contains(.,'blah')]
I want to know the index of the matched 'th' element ? i.e. was it the first cell or the second one .. or .. nth.
Upvotes: 1
Views: 58
Reputation: 106
I have used the same functionality in ruby
. But in Java
you can try something like this in Java
:
String path = driver.findElement(By.xpath("//th[contains(.,'blah')]")).toString();
String lastElement = path.substring(path.lastIndexOf('/') + 1);
And for getting count of your th
I'm using following code in ruby
:
int columnNo = lastElement .match(/(?<=\[).+?(?=\])/).to_s.to_i
You can use appropriate code in java
. Please correct if any typecasting errors. I'm not a java guy.
Upvotes: 0
Reputation: 52685
You can try to implement below code (Python
example):
all_elements = driver.find_elements_by_xpath('//table/thead/tr/th')
target_element = driver.find_element_by_xpath('//table/thead/tr/th[contains(.,"blah")]')
print(all_elements.index(target_element))
Python
list
has built-in method index()
which allow to get index of element in a list. Let me know if you need a solution in another programming language
Upvotes: 2