eastwater
eastwater

Reputation: 5640

Selenium XPath: ancestor does not contain

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.

Upvotes: 1

Views: 1533

Answers (3)

supputuri
supputuri

Reputation: 14145

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']]

Upvotes: 0

Jack Fleeting
Jack Fleeting

Reputation: 24930

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

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

Upvotes: 0

zx485
zx485

Reputation: 29052

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>.

Upvotes: 2

Related Questions