Hervé Tchikladzé Hervé Tchikladzé - 1 month ago 12
Javascript Question

Protractor - find element with "neighbour"

I'm currently creating tests with protractor and phantomjs.

What I'm trying to do is pretty simple, here is my html code containing the element I want to click.

<tr class="moo" role="foo"
<td class="bar"
<input class="toto" value="42" type="checkbox"></input>
</td>
<td class="titi"
<a href="/path/to/something">Test</a>
</td>
</tr>


Here I need to click the checkbox element, quite easy actually with :
element(by.xpath("//input[@type='checkbox']")).click();


But the problem is that there is many checkbox elements and the only difference between them is the "a" line with the text (Test in this example) that changes.

My question is : how can I specify that I want to click the checkbox Where the text in "a" line is "Test" ?

Answer

Use a CSS selector to find the row and then the cell:

element(by.cssContainingText('tr[role="foo"]', 'Test'))
  .element(by.css('input'))
  .click();

Or with an XPath to find the cell with a single call:

element(by.xpath('//tr[td/a/text()="Test"]//input'))
  .click();
Comments