Reputation: 3071
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
Reputation: 193088
Presuming the conditions below:
myclass
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
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
Reputation: 338158
//span[contains(@class, 'myclass') and text() = 'qwerty']
or
//span[contains(@class, 'myclass') and normalize-space(text()) = 'qwerty']
Upvotes: 96