Kirill Lappo
Kirill Lappo

Reputation: 113

C# Selenium Web Driver and CSS : Start point

I have the next tags structure:

<body>
   <parent>
       <nested/>
   </parent>
</body>

I do the following thing:

IWebDriver _driver;

var parent = _driver.FindElement(By.Css("parent"));
var nested = parent.FindElement(By.Css("parent nested"));

Notice, I need to find nested element only this way: at first I find parent tag, then I use parent as a start point to find nested one. But when I use logically wrong locator("parent nested", because together "parent parent nested" is wrong locator), parent.FindElement returns(!) me correct IWebElement, just like if I searched from the top of DOM model.

The interesting thing is that when I do

var nested = parent.FindElement(By.Css("parent"));

it throws element not found exception.

I think I understand something wrong or just don't know something. How does it work? How I can avoid problem of "parent parent nested" ?

Upvotes: 2

Views: 264

Answers (2)

Naveen Kumar R B
Naveen Kumar R B

Reputation: 6398

cssSelectors will be evaluated from right to left.

that means first children will be evaluated and then check whether their parent exists.

In your case,

var nested = parent.FindElement(By.Css("parent nested"));

first, check whether nested element is present as a child in the DOM (here, nested element). if present, then check whether parent is its parent.

and

var nested = parent.FindElement(By.Css("parent"));

here, parent will be checked whether it is a child of the given element (calling on parent). but it is not. so, gives NoSuchElementException

Reference:

  1. Why do browsers match CSS selectors from right to left?

Upvotes: 2

NarendraR
NarendraR

Reputation: 7708

I think here you are using wrong way thats why you are getting error

var nested = parent.FindElement(By.Css("parent"));

Here you are doing -

"first find parent tag, then I use parent as a start point to find parent tag itself"

which is wrong. There can be different ways to get this -

  1. make parent tag as start point and find child tag -

var child= driver.FindElement(By.Css("parent")).FindElement(By.Css("nested"));

  1. Directly find child tag -

var child= driver.FindElement(By.Css("parent nested"));

Upvotes: 3

Related Questions