--- title: Xpath layout: default --- CSS equivalents --------------- | CSS | Xpath | | --- | --- | | `div p` | `//div//p` | | `ul > li` | `//ul/li` | | `div > *` | `//div/*` | | `h1 ~ ul` | `//h1/following-sibling::ul` | | `h1 ~ #id` | `//h1/following-sibling::[@id="id"]` | | --- | --- | | `:root` | `/` | | `:root > body` | `/body` | | --- | --- | | `input[type="submit"]` | `//input[@type="submit"]` | | `a[href^='/']` | `//a[starts-with(@href, '/')]` | | `a[href$='pdf']` | `//a[ends-with(@href, '.pdf')]` | | --- | --- | | `#id` | `//[@id="id"]` | | `.class` | `//[@class="class"]` *...see below* | | --- | --- | | `ul > li:first-child` | `//ul/li[1]` | | `ul > li:nth-child(2)` | `//ul/li[2]` | | `ul > li:last-child` | `//ul/li[last()]` | | --- | --- | | `li#id:first-child` | `//li[@id="id"][1]` | | --- | --- | | `a:first-child` | `//a[1]` | | `a:last-child` | `//a[last()]` | | `li:first-of-type` | `//li[not(preceding-sibling::li)]` | {:.greycode.no-head} ### Class check Xpath doesn't have the "check if part of space-separated list" operator, so this is the workaround: ```sh //div[contains(concat(' ',normalize-space(@class),' '),' foobar ')] ``` ### jQuery equivalents For things that CSS alone can't do. | jQuery | Xpath | | ------ | --- | | `$('ul > li').parent()` | `//ul/li/..` | | `$('li').closest('section')` | `//li/ancestor-or-self::section` | | `$('a').attr('href')` | `//a/@href` | | `$('span').text()` | `//span/text()` | {:.greycode.no-head} Expressions ----------- ### Prefixes Begin your expression with any of these. | Prefix | Example | | --- | --- | | `//` *anywhere* | `//hr[@class='edge']` | | `./` *relative* | `./a` | | `/` *root* | `/html/body/div` | {:.greycode.no-head} ### Axes Separate your steps with `/`. Use two (`//`) if you don't want direct descendants. | Axis | Example | | --- | --- | | `/` *child* | `//ul/li/a` | | `//` *descendant* | `//[@id="list"]//a` | {:.greycode.no-head} ### Selecting node data ```sh //a #=> //a/text() #=> "Go home" //a/@href #=> "index.html" //a/* #=> All a's child elements ``` Predicates ---------- ### Predicates (`[]`) Restricts a nodeset only if some condition is true. They can be chained. ```sh //div[true()] //div[@class="head"] //div[@class="head"][@id="top"] ``` ### Operators Use operators to make conditionals. ```sh # Comparison //a[@id = "xyz"] //a[@id != "xyz"] //a[@price > 25] ``` ```sh # Logic (and/or) //div[@id="head" and position()=2] //div[(x and y) or not(z)] ``` ### Using nodes You can use nodes inside predicates. ```sh # Use them inside functions //ul[count(li) > 2] //ul[count(li[@class='hide']) > 0] ``` ```sh # This returns `