Skip to content

How to Find an Element by CSS Class Name with XPath

XPath is a query language used to locate elements on a web page by evaluating XML path expressions against the HTML DOM structure.

The standard syntax for an XPath expression is:

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

There are different types of locators that are used to find elements:

Locator TypeDescription
IDFinds an element by its id attribute.
ClassnameFinds an element by its class attribute.
NameFinds an element by its name attribute.
Link textFinds a hyperlink by its visible text.
XPathFinds elements using XPath expressions.
CSS pathFinds elements using CSS selectors.

In this snippet, we’ll focus on finding an element by its class name.

Let’s see how we can find a <div> element with the class name box. We’ll use the // path expression and the contains() function. This function can also match elements with partial class names.

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

This will select all <div> elements whose class attribute contains the string box. It can also match cases like class="firstbox" or class="secondbox".

You can also use the following pattern to ensure an exact class match:

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

To handle extra whitespace reliably, you can use the normalize-space() function:

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

Dual-run preview — compare with live Symfony routes.