How to access a specific child div using xpath? (Selenium Java)

14,028

Solution 1

Your XPath is wrong! .. means "parent of". Single dot . would mean relative to current location.

Try: panel.findElement(By.xpath(".//div[@class='foo2']")

Solution 2

How about you use descendant

panel.findElement(By.xpath("//div[@class='panel']/descendant::div[@class='foo2']"));

Source http://www.caucho.com/resin-3.1/doc/xpath.xtp#descendant

Share:
14,028

Related videos on Youtube

Matt
Author by

Matt

Updated on June 04, 2022

Comments

  • Matt
    Matt almost 2 years

    I have the following html code:

    <div class="panel">
        <div class = "heading">
            <span class="wName">Name</span>
            <div class="foo1" style="display: none;"></div>
            <div class="foo2" style="display: none;"></div>
        </div>
    </div>
    

    I already located element panel and I'm trying to test when foo2 doesn't appear with the following line of code:

    if (panel.findElement(By.xpath("../div[@class='foo2']")).getCssValue("display").equals("none"))
    

    I'm not sure why this won't retrieve the element properly.

  • ddavison
    ddavison over 9 years
    alternatively, you can use the cleaner CSS solution. @OP. By.cssSelector("div.foo2")
  • SiKing
    SiKing over 9 years
    @sircapsalot If we are going after "clean", then I think By.className("foo2") wins out.
  • ddavison
    ddavison over 9 years
    or of course we can go the "less clean" route. By.cssSelector("div[class~='panel']>div[class~='heading']>di‌​v[class]:nth-child(3‌​)") ;)
  • VGR
    VGR over 9 years
    Actually, since the div of interest isn't a direct child of the panel, the XPath needs to be .//div[@class='foo2'], or ./div/div[@class='foo2'], or ./*/div[@class='foo2'], etc.