Find the div with class "bar" whose ancestor does not have class "foo" within the scope of top-level "foo". For example,

<div class="foo">
    <div class="foo">
         <div><div>
         <div class="bar"> </div>
         </div></div>
    </div>

    <div class="bar"> </div>
</div>

Find the bar not inside the nested "foo".

And the XPath I tried is:

WebElement root = driver.findElement(By.xpath("//div[@class='foo']"));
root.findElements(By.xpath(".//div[not(contains(@class, 'foo'))]//div[contains(@class, 'bar')]"));

But the XPath returns two elements. Also tried css selector:

root.findElements(By.cssSelector(":not(.foo) .bar"));

Not working either.

3 Answers

1
zx485 On

Try this XPath-1.0 expression:

//div[contains(@class, 'bar') and not(ancestor::*[@class='foo'])]

It only returns one item: the desired <div class="bar"> </div>.

0
Jack Fleeting On

This one returns only the 2nd bar (at least when I run it...)

//*[@class='bar'][(parent::div[@class='foo'])]
0
supputuri On

If you are trying to access the direct child div with bar class, then here is the xpath.

//div[@class='bar' and parent::div[@class='foo']]