Steve Staple
Steve Staple

Reputation: 3289

Java Selenium WebElement element.findElements not working as expected

I am testing a web application using Java and Selenium. I am trying to click a button on a page where two buttons exist with the same classname and text. So I find the parent element first, and then look for my button among its child elements. I am executing the following and getting unexpected results.

public static List<WebElement> findSubElementsUsingHtmlXpathClass(String htmlElement,
        String className, WebElement parent) {
    String xPathString="//" + htmlElement + "[contains(@class, '" + className + "')]";

    List<WebElement> elements = parent.findElements(By.xpath(xPathString));
    return elements;
}

This is returning elements that do not belong to the parent element.

This is where I am calling it from:

String htmlElement = "div";
    String className = "tabs-container";
    List<WebElement> elements = Common.findElementsUsingHtmlXpathClass(driver, htmlElement, className);
    Common.myPrint(thisClass + " no of elements found: " + elements.size());
    for (WebElement element : elements) {
        // outerHTML: <input class="form-control btn btn-info" value="Create item"
        // type="button">
        // inner:
        String htmlElement2 = "input";
        String className2 = "form-control btn btn-info";
        String textToFind = "Create item";
        List<WebElement> subElements = Common.findSubElementsUsingHtmlXpathClass(htmlElement2, className2,
                element);HTML

Am I missing something?

I have been able to work around this, by simply ignoring the first elemnt it returns, but this can only be guaranteed in this specific case.

Upvotes: 0

Views: 847

Answers (2)

Subburaj
Subburaj

Reputation: 2334

Your XPath needs to be changed as below (. needs to be added before the double slash).you need to select the child element from the current parent element .So, in Xpath, . needs to be specified to indicate it as current node.

public static List<WebElement> findSubElementsUsingHtmlXpathClass(String htmlElement,
        String className, WebElement parent) {
    String xPathString=".//" + htmlElement + "[contains(@class, '" + className + "')]";

    List<WebElement> elements = parent.findElements(By.xpath(xPathString));
    return elements;
}

Upvotes: 2

JanZ
JanZ

Reputation: 584

Try using CSS-Selector instead of XPath:

public static List<WebElement> findSubElementsUsingCSS(String className, WebElement parent) {
        String cssString="." + className;

        List<WebElement> elements = parent.findElements(By.cssSelector(cssString));
        return elements;
    }

Upvotes: 0

Related Questions