How to get element index on the basis of its text using Java and Selenium?

5k views Asked by At

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?

2

There are 2 answers

0
David Genn On

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

More details here.

0
lilalinux On

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
}