hot_like_sauce
hot_like_sauce

Reputation: 5

Protractor Locator for elements of same class

I'm new to Protractor and E2E testing and want to determine whether my approach to CSS locators is correct for identical elements of the same class.

I have an HTML Fiddle here that depicts a webpage with two div elements, each containing two buttons: the buttons are all of the same class. HTML follows:

<!DOCTYPE html>
<html>
<body>
  <div>
    <button class="btn1" tooltip="Color">
              <span class="color-indicator" style="background-color: rgb(0, 0, 0);">
    </button>
    <button class="btn1" tooltip="Background Color">
              <span class="color-indicator" style="background-color: rgb(50, 50, 50);">
    </button>
  </div>
  <div>
    <button class="btn1" tooltip="Color">
              <span class="color-indicator" style="background-color: rgb(0, 0, 0);">
    </button>
    <button class="btn1" tooltip="Background Color">
              <span class="color-indicator" style="background-color: rgb(50, 50, 50);">
    </button>
  </div>
</body>
</html>

I need to click each button element in each div. The buttons can be accessed by element(by.css()) Locator using their CSS selectors (e.g. "body > div:nth-child(1) > button:nth-child(1)") but is there a better way to access these items?

My website has many instances like this, and I'd like to know if there is a better way to access elements like this, other than hardcoding their nth-child numbers in my it() scripts. The elements on the webpages might be reordered in the future, and so using numbering might result in broken cases down the road.

Thank you :-)

Upvotes: 0

Views: 768

Answers (1)

Joaquin Casco
Joaquin Casco

Reputation: 734

If you know the exact amount of buttons with the same class, you can locate them with css selector; in this case, there are 4, so it'd look like this::

element.all(by.css('.btn1')).get(0);
element.all(by.css('.btn1')).get(1);
element.all(by.css('.btn1')).get(2);
element.all(by.css('.btn1')).get(3);

Let me know if it helped!

Upvotes: 0

Related Questions