Skip to content

XPath and CSS Selectors: A Practical Cheat Sheet

Use this guide to pick the right selector for the job: start with element and hierarchy, then refine by position, attribute, partial attribute value, relative axis, or a predicate function. Each pattern below pairs the CSS form with its XPath counterpart where one exists, and notes where XPath offers the extra capability.

Copying an XPath expression from Chrome DevTools

A copied expression is a starting point, not a finished selector. It often encodes the full path from the document root, so it can break when a wrapper element is added. Use it to identify the target, then simplify it with the patterns below and test it against the live page.

Workflow checklist:

  • Open DevTools with F12 or right-click and choose Inspect.
  • Highlight the target with the element selector tool.
  • Right-click the highlighted entry and choose Copy, then Copy XPath.
  • Paste the expression into your code, then shorten it: keep the final element name, add an attribute or position predicate, and drop unnecessary ancestors.
  • Re-test after any page layout change, because a long absolute path is the most fragile form.

Node selection: element and hierarchy

Choose by element name and hierarchy first. CSS element selects every matching tag anywhere in the document; XPath //element does the same. XPath /element is narrower: it targets the root element only. To require a specific parent, CSS uses parent element, while XPath uses //parent/element. The wildcard * in CSS and //* in XPath select every element.

Worked example: to collect every div, use CSS div or XPath //div. If you only want divs inside a section, switch to section div or //section/div so you do not pick up unrelated divs elsewhere on the page.

Position-based selection

Use position when several siblings share the same tag and you need a specific one. CSS distinguishes first of its type from first child; XPath predicates [1], [n], and [last()] express the same idea by index.

  • First of its type: CSS :first-of-type, XPath [1]
  • Nth of its type: CSS :nth-of-type(n), XPath [n]
  • Last of its type: CSS :last-of-type, XPath [last()]
  • First child of its parent: CSS :first-child, XPath //*[1]
  • Last child of its parent: CSS :last-child, XPath //*[last()]

Worked example: for the first paragraph, use CSS p:first-of-type or XPath //p[1]. Prefer of-type when other tags are interleaved among the siblings, and child when order among all children matters.

Attribute selection

Attribute selectors narrow a result set by presence or exact value. CSS [attribute] matches any element carrying that attribute; XPath //*[@attribute] does the same, and //element[@attribute] restricts it to one tag. For an exact value, CSS [attribute="value"] corresponds to XPath //*[@attribute="value"] or //element[@attribute="value"].

Worked example: to find elements whose class is exactly example, use CSS [class="example"] or XPath //*[@class="example"]. Add the tag name on either side when the same attribute appears on several element types.

Attribute value matching

Partial matching is where the two syntaxes diverge most visibly. CSS uses three operators, and XPath uses three string functions:

  • Starts with: CSS [attribute^="value"], XPath [starts-with(@attribute, "value")]
  • Ends with: CSS [attribute$="value"], XPath [ends-with(@attribute, "value")]
  • Contains: CSS [attribute*="value"], XPath [contains(@attribute, "value")]

Worked example: for classes beginning with btn, use CSS [class^="btn"] or XPath [starts-with(@class, "btn")]. Partial matches are useful for generated or variant class names, but they can over-match, so confirm the result set before relying on them.

XPath axes

Axes let XPath move relative to a context node instead of always starting from the root. CSS has no direct equivalent for most of these, so reach for XPath when the relationship, not the tag, defines the target.

  • ancestor: all ancestors of the context node, for example //div/ancestor::*
  • ancestor-or-self: the context node plus its ancestors
  • child: immediate children, for example //div/child::*
  • descendant: all descendants at any depth
  • descendant-or-self: the context node plus all descendants
  • following: all nodes after the context node in the document
  • following-sibling: siblings after the context node
  • parent: the immediate parent
  • preceding: all nodes before the context node in the document
  • preceding-sibling: siblings before the context node
  • self: the context node itself

Worked example: to get every child of a div, use XPath //div/child::*. Choose descendant when depth varies, and child when only direct children count.

XPath operators and functions

Predicates become expressive when you combine comparisons, logic, and functions. Comparison operators (=, !=, <, >, <=, >=) test values inside a predicate. Logical operators (and, or, not()) combine or negate conditions. Node-set functions include count(node-set), which returns how many nodes match, and position(), which returns the context node's position in its list. String functions include contains, starts-with, ends-with, substring, string-length, and concat.

Worked example: to test whether an attribute contains example, use XPath [contains(@attribute, "example")]. Combine it with and or or when an element must satisfy more than one condition, and use count() when you need the number of matches rather than the matches themselves.

Choosing between CSS and XPath

Decision checklist:

  • Need every element of a tag? Use CSS element or XPath //element.
  • Need a specific sibling? Use a position pattern such as :nth-of-type(n) or [n].
  • Need an attribute present or exactly equal? Use [attribute] or [attribute="value"], with @attribute in XPath.
  • Need a prefix, suffix, or substring? Use ^=, $=, *= in CSS, or starts-with, ends-with, contains in XPath.
  • Need a relative relationship such as parent, sibling, or descendant? Use an XPath axis.
  • Need counting, logic, or string manipulation inside a predicate? Use XPath operators and functions.

Start simple, test against the page, and only add axes or functions when a plain selector cannot express the relationship you need.

Quick reference: common selector patterns
PatternCSSXPath
All elements of a tagelement//element
Children of a parentparent element//parent/element
First of its type:first-of-type[1]
Last child:last-child//*[last()]
Attribute present[attribute]//*[@attribute]
Attribute equals value[attribute="value"]//*[@attribute="value"]
Attribute starts with[attribute^="value"][starts-with(@attribute, "value")]
Attribute contains[attribute*="value"][contains(@attribute, "value")]
Children of a divdiv > *//div/child::*

XPath /element targets the root element only; //element searches the whole document.

Frequently asked questions

How do I copy an XPath expression in Chrome?

Open DevTools with F12 or Inspect, pick the element with the selector tool, right-click its entry, choose Copy then Copy XPath, and paste the expression into your code.

What is the CSS equivalent of //div or //p[1]?

CSS uses div, while XPath uses //div. CSS uses p:first-of-type, while XPath uses //p[1]. For a class value, CSS uses [class="example"], while XPath uses //*[@class="example"].

How do I match only part of an attribute value?

Use starts-with for a prefix, ends-with for a suffix, and contains for a substring. The matching CSS forms are ^=, $=, and *= respectively.

When should I use an XPath axis instead of a plain path?

Axes navigate relative to a context node: ancestor and descendant cover upward and downward trees, parent and child are immediate neighbours, self is the node itself, and following or preceding plus their sibling variants cover document order.