4 ms·
CSS is designed to be very fast, and because of that design choice it's less expressive. XPath is not going to beat CSS in speed, but it allows you to move thro
by err4nt 3y ago
CSS is designed to be very fast, and because of that design choice it's less expressive. XPath is not going to beat CSS in speed, but it allows you to move through the document in any direction (up and down in the DOM tree of elements, forward/back among siblings in the DOM tree, and forward and backward in document appearance order).
We use XPath at work from CSS with custom plugins, and use XPath in JavaScript for targeting elements that otherwise wouldn't be straightforward to select with CSS.
Another cool thing XPath does is have awareness of the text content of elements! //li[contains(.,"example")] would target all <li> elements with text content containing "example".
- masklinn 3y agoFWIW CSS now has “:has” which provides a form of general purpose predication, although afaik it still doesn’t have a :contains (that was proposed for CSS3 or something but I don’t think it got accepted). A huge part of XPath’s power though, and something you AFAIK can’t do in browsers, is extensibility. For instance selecting an element on the basis of a class is absolute hell in XPath 1.0 (and not great in 2.0 either, XPath 3.1’s `contains-token` finally made that not hell). But server-side you don’t care because pretty much all implementations allow installing your own functions so you can add your own `contains-token` or even `has-class` predicate and be on your way.