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')]
Related videos on Youtube
Author by
user1786107
Updated on July 09, 2022Comments
-
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 about 8 yearsThis solution did not work for me. This one did -- "and contains(., 'qwerty')". Found the solution here: stackoverflow.com/questions/19503721/…
-
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 about 8 yearsI 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 about 8 yearsWell, you're right. Having a cross-link is not all that bad.
-
Steph about 7 yearsthis didn't work for me, this did: //span[contains(@class, 'myclass') and contains(., 'querty')]
-
Evdzhan Mustafa over 6 yearsYay, more than a year later, I found my answer to help me. Bless me.
-
Mate Ajdukovic about 4 years@ Evdzhan it is nice when it happens. :)
-
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 usestext()
because the OP did in their question. With.
all contained text nodes are considered, including the nested ones.