HTML XPath Searching by class and text

106,750

Solution 1

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

or

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

Solution 2

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')]
Share:
106,750

Related videos on Youtube

user1786107
Author by

user1786107

Updated on July 09, 2022

Comments

  • user1786107
    user1786107 almost 2 years

    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)

  • Andrejs
    Andrejs about 8 years
    This solution did not work for me. This one did -- "and contains(., 'qwerty')". Found the solution here: stackoverflow.com/questions/19503721/…
  • Tomalak
    Tomalak about 8 years
    @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.
  • Andrejs
    Andrejs about 8 years
    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.
  • Tomalak
    Tomalak about 8 years
    Well, you're right. Having a cross-link is not all that bad.
  • Steph
    Steph about 7 years
    this didn't work for me, this did: //span[contains(@class, 'myclass') and contains(., 'querty')]
  • Evdzhan Mustafa
    Evdzhan Mustafa over 6 years
    Yay, more than a year later, I found my answer to help me. Bless me.
  • Mate Ajdukovic
    Mate Ajdukovic about 4 years
    @ Evdzhan it is nice when it happens. :)
  • Tomalak
    Tomalak over 3 years
    ...that's because text() only selects immediate text node children, i.e. it finds the 'ABC' in <span>ABC<b>XYZ</b></span>, 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.