Search code examples
javascriptcssprotractor

Get a sibling web element using css selector


How can I get a reference to the button? which is always a sibling of the text I'm searching for.

In protractor test:

let spanText = 'My text';
let spanRef = element(by.css('span[name=' + spanText + ']'));

Html:

<div>
  <span name="My text">My text</span>
  <button type="button">
    Click me!
  </button>
</div>

Solution

  • You can use the adjacent sibling selector (+):

    by.css('span[name=' + spanText + '] + button')
    

    Note that you may want to add quotes to surround spanText since it contains a space. See valid identifiers

    With quotes and using template literal syntax:

    by.css(`span[name="${spanText}"] + button`)