Appearance
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 Type | Description |
|---|---|
| ID | Finds an element by its id attribute. |
| Classname | Finds an element by its class attribute. |
| Name | Finds an element by its name attribute. |
| Link text | Finds a hyperlink by its visible text. |
| XPath | Finds elements using XPath expressions. |
| CSS path | Finds 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 ')]