user1786107
user1786107

Reputation: 3071

HTML XPath Searching by class and text

I want to find all elements in xpath by class and text. I have tried this but it does not work.

//*[contains(@class, 'myclass')]//*[text() = 'qwerty']

I am trying to find all elements that have a class of 'myclass' and the text is 'qwert' (these will be span elements)

Upvotes: 55

Views: 149763

Answers (3)

undetected Selenium
undetected Selenium

Reputation: 193088

Presuming the conditions below:

  • The class attribute contains only myclass
  • The innerText contains qwerty (without any leading and trailing spaces)

You can use the following solution:

//*[@class='myclass' and text()='qwerty']

Incase the innerText contains qwerty along with some leading and trailing spaces, you can use either of the following solutions:

  • Using normalize-space():

    //*[@class='myclass' and normalize-space()='qwerty']
    
  • Using contains():

    //*[@class='myclass' and contains(., 'qwerty')]
    

Upvotes: 3

Evdzhan Mustafa
Evdzhan Mustafa

Reputation: 3735

Generic solution for anyone looking for a XPath expression to search based on class and text:

Class is only "myclass":

//*[@class='myclass' and contains(text(),'qwerty')]

Class contains "myclass":

//*[contains(@class,'myclass') and contains(text(),'qwerty')]

Upvotes: 37

Tomalak
Tomalak

Reputation: 338158

//span[contains(@class, 'myclass') and text() = 'qwerty']

or

//span[contains(@class, 'myclass') and normalize-space(text()) = 'qwerty']

Upvotes: 96

Related Questions