3

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>

2 Answers 2

4

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`)
Sign up to request clarification or add additional context in comments.

1 Comment

Good job using a CSS selector for that.
1

Maybe help you:

Xpath:

  • //span[@name='My text']/following-sibling::button
  • //span[contains(text(),'My text')]/following-sibling::button
  • //div[span[@name='My text']]/button

CSS:

  • span[name='My text'] + button

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.