54

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)

James
  • 32,991
  • 4
  • 47
  • 70
user1786107
  • 2,921
  • 5
  • 24
  • 35

3 Answers3

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

or

//span[contains(@class, 'myclass') and normalize-space(text()) = 'qwerty']
Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • 5
    This solution did not work for me. This one did -- "and contains(., 'qwerty')". Found the solution here: http://stackoverflow.com/questions/19503721/xpath-find-a-node-whose-class-attribute-matches-a-value-and-whose-text-contains – Andrejs Jun 13 '16 at 12:08
  • 1
    @Andrey Writing "this did not for me" without telling what you did is not terribly useful. In any case, the above code is correct for the question in this thread, if your situation is different it should not be a surprise that you can't just copy and paste the code. – Tomalak Jun 13 '16 at 14:33
  • 4
    I didn't mean to insinuate that your answer is wrong. (especially given the number of upvotes). I do hope however that people will find my link useful if it doesn't work out for them for whatever reason. Regards. – Andrejs Jun 13 '16 at 14:44
  • Well, you're right. Having a cross-link is not all that bad. – Tomalak Jun 13 '16 at 15:26
  • 2
    this didn't work for me, this did: //span[contains(@class, 'myclass') and contains(., 'querty')] – Steph May 17 '17 at 17:30
  • ...that's because `text()` only selects immediate text node children, i.e. it finds the `'ABC'` in `ABCXYZ`, but not the `'XYZ'`. This answer uses `text()` because the OP did in their question. With `.` all contained text nodes are considered, including the nested ones. – Tomalak Feb 23 '21 at 09:16
35

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')]
Evdzhan Mustafa
  • 3,645
  • 1
  • 24
  • 40
3

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')]
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352