This popular Stack Overflow question explained why CSS selectors are parsed right to left. Are XPath queries evaluated in the same way? If this is dependent on implementation I’d appreciate knowing how libxml2 does it.
This popular Stack Overflow question explained why CSS selectors are parsed right to left.
Share
You should take another careful read at the accepted answer for that question you reference.
CSS selectors are evaluated right-to-left as an implementation detail for the specific scenario where a browser has a single element and is trying to determine which selectors in a CSS stylesheet apply to it. The reason browsers evaluate right-to-left in this case is because candidate selectors can be eliminated more quickly.
There is nothing inherent to CSS selectors that demands they be evaluated right-to-left or left-to-right. In fact, jQuery or
querySelectorAllwill evaluate from left-to-right, as the answer notes.In other words:
Scenario 1 fits best where you have an element to style (CSS) or an XSL stylesheet’s
template match="??"(XPath) and you have a large number of selectors or XPaths to test. Scenario 2 fits best when you have a single selector or XPath and you want all matching elements, as when you usequerySelectorAllor query a DOM.XPath expressions can be much more complex than CSS selectors, so there are probably XPaths where a right-to-left short-circuit evaluation is not possible or easy, but conceptually an XSLT engine could certainly try to do that. I don’t know if any do.
The most important thing to understand is, however a CSS selector or XPath is evaluated, it must give the same answer as if it were evaluated left-to-right over the entire document tree. So you don’t need to evaluate left-to-right, but you must act as if you did because the specifications define them this way.