1

I want to click an element by the text of a span who is the child of the element. How do I do this?

<button type="button" class="alert-button ion-focusable ion-activatable sc-ion-alert-md" tabindex="0"><span class="alert-button-inner sc-ion-alert-md">OK</span><ion-ripple-effect class="sc-ion-alert-md md hydrated" role="presentation"></ion-ripple-effect></button>

This is what I have tried but it didn't work.

@FindBy(css = "button[span:contains('OK')]")

2 Answers 2

1

Selenium doesn't supports the :contains pseudo-class anymore as @jari.bakken in their comment confirms:

AFAICT, the :contains pseudo-class isn't in the CSS spec and is not supported by either Firefox or Chrome (even outside WebDriver).

Further @dawagner in their comment also mentions:

contains isn't a valid CSS3 selector; because of this several browsers don't natively support contains, so Selenium (and WebDriver) don't claim to support it._


Solution

However you can still use the other attributes to construct a CssSelector to identify the element as follows:

@FindBy(css = "button.alert-button.ion-focusable.ion-activatable.sc-ion-alert-md span.alert-button-inner.sc-ion-alert-md")

As an alternative you can also use either of the following Xpath based locator strategies:

@FindBy(xpath = "//button[@class='alert-button ion-focusable ion-activatable sc-ion-alert-md']//span[@class='alert-button-inner sc-ion-alert-md']")

Using the innerText:

@FindBy(xpath = "//button[@class='alert-button ion-focusable ion-activatable sc-ion-alert-md']//span[@class='alert-button-inner sc-ion-alert-md' and text()='OK']")

or even:

@FindBy(xpath = "//span[@class='alert-button-inner sc-ion-alert-md' and text()='OK']")

even possibly:

@FindBy(xpath = "//span[text()='OK']")
Sign up to request clarification or add additional context in comments.

Comments

1

CSS Selectors with Selenium do not support locating elements by their text content. Only XPath supports that.
Try this XPath:

//button//span[text()='OK']

or

//button//span[contains(.,'OK')]

or

//button//span[contains(text(),'OK')]

So the element could be defined as following

@FindBy(xpath= "//button//span[text()='OK']")

Or

@FindBy(xpath= "//button//span[contains(.,'OK')]")

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.