Skip to content
Greg Bowler edited this page Feb 19, 2022 · 4 revisions

Introduction

Both CSS selectors and XPath queries achieve the same goal: obtaining a reference to one or more elements within a document, by using a "locator" string, but CSS selectors are generally simpler than XPath queries, and with their widespread use within web browsers for styling content, CSS selectors are typically understood by a lot more developers.

Some tools, such as PHP's DOMDocument, require the use of XPath queries to traverse the trees of elements. So in order to be able to use CSS selectors within a DOM Document, a CSS selector needs to be translated into an XPath query. This is exactly what PhpGt/CssXPath does.

Comparing CSS selectors with equivalent XPath queries

CSS selectors are often easier to read and write, and are often much more terse compared to XPath queries. This is because an XPath query has much more power and flexibility, but more often than not a CSS selector can achieve the goal of selecting the element(s) the developer needs.

The table below compares some commonly-used CSS selectors with the equivalent XPath queries:

CSS XPath
p .//p
form label>span .//form//label/span
body>header nav li>a .//body/header//nav//li/a
.create-new button[value=submit] .//*[contains(concat(" ",normalize-space(@class)," ")," create-new ")]//button[@value="submit"]
#menu nav[selected] li.highlight .//*[@id="menu"]//nav[@selected]//li[contains(concat(" ",normalize-space(@class)," ")," highlight ")]

Using PhpGt/CssXPath

// TODO.

Clone this wiki locally