brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: $x() runs an XPath query in the DevTools console

Devtools
~/tips/tip-devtools-console-xpath-x

$x(path [, startNode])

Finds page elements with an XPath expression and returns them as an array.

CSS selectors can’t select an element by its text. XPath can, and Chrome DevTools has a console helper for it.

$x(path [, startNode])

$x() returns an array of DOM elements that match the XPath expression. The docs give $x("//p") for all paragraphs and $x("//p[a]") for paragraphs that contain a link.

$x("//a[contains(text(), 'Download')]")

That finds every link whose text contains the word Download. Hover an element in the result and it is highlighted on the page. The optional second argument is a node to start from, for example $x('.//li', $0) to search only inside the element you selected in the Elements panel.

The caveat is that $x is a console helper. It exists in the DevTools console only, so don’t paste it into your page’s scripts. There you want document.evaluate(), which is much more verbose.

XPath is also a quick way to climb up the tree. $x("//span[text()='Total']/..") returns the parent of the span, which a CSS selector can’t do in most browsers. Handy when you only know the label of a field and want the whole row.

Two sibling helpers from the same docs page are worth knowing. $$(selector) returns an array of elements matching a CSS selector, which is the same as Array.from(document.querySelectorAll()). $(selector) returns the first match. If a library such as jQuery defines $ on the page, it overrides that helper.

Further reading: Console utilities reference

More Devtools tips Clear site data for one site from Chrome DevTools user.id === 42 @media (prefers-color-scheme: dark) { queryObjects(Promise) inspect(document.querySelector('footer')) All Devtools tips (22) All topics

Link