So there's a table of links on the web page, and I need the element indices. I know the names of the links. I tried the selenium.getElementIndex().intValue()
command, hoping for an integer index.
But the getElementIndex()
function requires a String locator as parameter. Not sure what to pass, since the only information about that element that I have is its name.
Also, what kind of value does the getElementIndex()
return?
Asked
Active
Viewed 4,875 times
0

Arka
- 35
- 2
- 9
2 Answers
2
This code will return the index of an element relative to it's parent. Only siblings with the same tag will be counted
int getElementIndex(WebElement element) {
WebElement parent = element.findElement(By.xpath(".."));
List<WebElement> siblings = parent.findElements(By.xpath("./" + element.getTagName()));
int i=0;
for (WebElement sibling : siblings) {
if (element.equals(sibling)) {
return i;
} else {
i++;
}
}
throw new NotFoundException(); // Should never happen
}

lilalinux
- 2,903
- 3
- 43
- 53
1
Here's the javadoc for Selenium.getElementIndex()
.
It will return an Number
which is the index of the element selected and takes a String locator
which is used to locate the element you're interested in on the HTML page and can be a number of things eg: -
- the id of the element
- some xPath
- etc

David Genn
- 709
- 4
- 11