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
Related videos on Youtube
Author by
Matt
Updated on June 04, 2022Comments
-
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 over 9 yearsalternatively, you can use the cleaner CSS solution. @OP.
By.cssSelector("div.foo2")
-
SiKing over 9 years@sircapsalot If we are going after "clean", then I think
By.className("foo2")
wins out. -
ddavison over 9 yearsor of course we can go the "less clean" route.
By.cssSelector("div[class~='panel']>div[class~='heading']>div[class]:nth-child(3)")
;)
-
VGR over 9 yearsActually, 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.