user1233547
user1233547

Reputation: 19

Nested findElement where first is xpath and second is css, working not as expected

Here is how my html source looks like.

      <tr>
        <td class='first'>User Name</td>
        <td class='last'>
          <input/>
        </td>
      </tr>

Now, when I tried to locate input tag I mistakenly wrote my code like

driver.findElement(By.xpath("//tr/td[@class='last']")).findElement(By.cssSelector("td.last>input"))

it successfully located the input tag, it seems a bit confusing to me because in my first findElement I've already reached till the td tag now again in second findElement I started from same td tag. I think it should throw NoSuchElement exception. Again I tried it with different combinations of By methods but it failed to locate and fired the NoSuchElement exception. Even I tried it like below and here it fired the NoSuchElement exception:

driver.findElement(By.xpath("//tr/td[@class='last']")).findElement(By.cssSelector("td.last"))

can any one please help me with the reason of this abnormal behaviour in first case where it located the input element successfully.

Upvotes: 1

Views: 1310

Answers (1)

Subh
Subh

Reputation: 4424

Your code is essentially correct. And, this is indeed a normal behavior.

 driver.findElement(By.xpath("//tr/td[@class='last']")).findElement(By.cssSelector("td.last>input"))

The first "findElement" part locates the td class with class 'last'. Now, the second "findElement" must locate an element that resides under the element, located by the first "findElement" part. And, that's exactly what it does. The cssselector points to the "input" tag under the td class with class 'last'. It doesn't matter where you have started it. In fact, what matters is the located element is "input" only.

Hope this helps.!!

Upvotes: 1

Related Questions