Testing / Selenium Interview questions
What is the difference between XPath and CSS selectors?
Both locate elements by describing their position or attributes in the DOM, but they differ in syntax, direction, and capability.
| XPath | CSS Selector |
| Can traverse both up and down the DOM tree | Generally only traverses downward/sideways |
| Can match on text content directly | Cannot match by visible text natively |
| Generally slower to evaluate | Generally faster, native to the browser engine |
A concrete example of XPath's extra reach: //label[text()='Email']/following-sibling::input finds an input based on a label's text and its position relative to it - something a CSS selector alone cannot express, since CSS has no way to search by text content or move to a preceding/following sibling based on content.
More Related questions...