How to find by class name in XPath?

Member

by elnora , in category: HTML/CSS , a year ago

How to find by class name in XPath?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by dorothea_mohr , a year ago

@elnora 

To find an element by class name in XPath, you can use the contains function. For example, to find an element with the class example-class, you can use the following XPath expression:

1
//*[contains(@class, 'example-class')]


This will select any element that has a class attribute containing the string 'example-class'. If you want to select only elements with a class attribute that consists solely of the string 'example-class', you can use the following expression:

1
//*[@class='example-class']


Note that the class attribute can contain multiple class names, separated by spaces. The contains function will match any element that has the specified class name as one of its class names, while the second expression will only match elements with a class attribute that consists solely of the specified class name.


You can also use the contains function to search for elements with multiple class names. For example, to find elements with both the example-class-1 and example-class-2 class names, you can use the following expression:

1
//*[contains(@class, 'example-class-1') and contains(@class, 'example-class-2')]


This will select any element that has both of the specified class names as part of its class attribute.