Evaluate and validate XPath/CSS selectors in Chrome Developer Tools
Recently Updated - May 30, 2017
Google Chrome provides a built-in debugging tool called "Chrome DevTools" out of the box, which includes a handy feature that can evaluate or validate XPath/CSS selectors without any third party extensions.
This can be done by two approaches:
- Use the search function inside
Elements
panel to evaluate XPath/CSS selectors and highlight matching nodes in the DOM. - Execute tokens
$x("some_xpath")
or$$("css-selectors")
inConsole
panel, which will both evaluate and validate.
From Elements panel
- Press
F12
to open up Chrome DevTools. Elements
panel should be opened by default.- Press
Ctrl
+F
to enable DOM searching in the panel. - Type in XPath or CSS selectors to evaluate.
- If there are matched elements, they will be highlighted in DOM.
However, if there are matching strings inside DOM, they will be considered as valid results as well. For example, CSS selectorheader
should match everything (inline CSS, scripts etc.) that contains the wordheader
, instead of match only elements.
From Console panel
- Press
F12
to open up Chrome DevTools. - Switch to
Console
panel. - Type in XPath like
$x(".//header")
to evaluate and validate. - Type in CSS selectors like
$$("header")
to evaluate and validate. - Check results returned from console execution.
- If elements are matched, they will be returned in a list. Otherwise an empty list
[ ]
is shown.
$x(".//article")
[<article class="unit-article layout-post">…</article>]$x(".//not-a-tag")
[ ]- If the XPath or CSS selector is invalid, an exception will be shown in red text. For example:
$x(".//header/")
SyntaxError: Failed to execute 'evaluate' on 'Document': The string './/header/' is not a valid XPath expression.$$("header[id=]")
SyntaxError: Failed to execute 'querySelectorAll' on 'Document': 'header[id=]' is not a valid selector. - If elements are matched, they will be returned in a list. Otherwise an empty list
Pros and cons
Advantages of one approach are pretty much considered as the cons of another method, and vice versa.
From 'Elements' panel | From 'Console' panel |
---|---|
Pros | Cons |
Quick and easy accessibility | Need to switch panel and extra typing |
Results are directly highlighted in DOM | Results are shown in a list Need to right click and go back to 'Element' panel |
Result count is displayed | (Lastest Chrome DevTools can show the count now) |
Cons | Pros |
All matched strings are also counted in | Will only match elements |
Only evaluates, doesn't validate Invalid locators will just return nothing | Throw exceptions if locator is invalid |
- | Can be used in console immediately for other purposes |