How to Find an Element by CSS Class Name with XPath

XPath is a syntax or language helping to find the location of any element on the web page by using XML path expression. To find an element, it uses HTML DOM structure.

The standard syntax for creating XPath is the following:

Xpath=//tagname[@attribute='value']

There are different types of locators that are used to find the element.







XPath Locator The element to be found
ID Finds the element by ID.
Classname Finds the element by Classname.
Name Finds the element by name.
Link text Finds the element by text of the link.
XPath Finds the dynamic element.
CSS path Locates elements without name, class or ID.

In our snippet, we’re interested in the case when there is a need to find an element by its class name.

Let’s see how we can find a <div> element with a class name “box”. We’ll need the //* path expression and the contains() method. This method can also find the element with a partial text.

//div[contains(@class, 'box')]

This will select all elements in the document. It can also match such cases as class=”firstbox” or “secondbox”.

You can also use the following:

//div[contains(concat(' ', @class, ' '), ' box ')]

To be sure that it will match correctly, you can use the normalize-space function, which cleans random whitespace characters around the class name:

//div[contains(concat(' ', normalize-space(@class), ' '), ' box ')]