A. Duff
A. Duff

Reputation: 4309

Get first element in protractor

I want to verify the number of table rows in protractor, on a page in which tables of this type appear more than once. I've been trying to use the first-of-type selector, but it seems to be catching both tables because they do not appear side by side.

For example, given this HTML:

<div>
  <table class="foo">
    <tr>
      <th>First row</th>
      <th>Second row</th>
      <th>Third row</th>
      <th>Fourth row</th>
    </tr>
  </table>
</div>
<div>
  <table class="foo">
    <tr>
      <th>First row</th>
      <th>Second row</th>
      <th>Third row</th>
      <th>Fourth row</th>
    </tr>
  </table>
</div>

And this protractor code:

element.all(by.css('table:first-of-type tr:first-of-type th')).then(function (elements) {
  expect(elements.length).toBe(4);
});

Protractor is failing on the grounds that there are 8 elements and not 4. It seems the table:first-of-type selector is catching both elements, since they're both the first children of their parent div components. My project is structured in such a way that it's better not to add individual classes to each wrapping div.

Is there a way to get the first element found in Protractor and then search its child elements?

Upvotes: 6

Views: 8832

Answers (2)

alecxe
alecxe

Reputation: 473833

You can certainly do it the way @cnishina suggested (and I would actually prefer his approach over making a long CSS selector), but if you want to continue using a single CSS selector for this problem, you should also apply the first-of-type (or first-child) to the parent div:

div:first-of-type > table:first-of-type > tr:first-of-type > th

I've also added the > to enforce the direct parent-child relationships.

Upvotes: 5

craig
craig

Reputation: 5016

I have not used :first-of-type as a css selector in Protractor; however, you could get the first table with all th's and then check to see if the count is 4.

expect(element.all(by.css('table')).first().all(by.css('th')).count()).toBe(4);

Upvotes: 6

Related Questions