jQuery has() selector: a discussion

I had a brief discussion with Boris Zbarsky on www-style about the possibility of implementing the jQuery's E:has(F) selector in the current CSS specification.

Boris correctly pointed out that my proposal would be far from being easy to implement because of the existing differences between JavaScript and other programming languages, such as C++ (the Firefox's source code is actually written in this language, as you can see at http://mxr.mozilla.org).

In a nutshell, JavaScript works with single DOM snapshots, while the CSS parser works with a global token stream (see Firefox's nsCSSScanner.cpp). For example, suppose that we want to stylize an h2 element based on the presence of an a element within it. We could write the following CSS rule:

h2:has(a) {
  color: green;

Consider the fact that we're actually working with the following DOM structure:

h2    #element
  a    #element

To properly select the h2 element, the CSS parser should adopt a DOM approach, that is, it should create a whole object model automatically whenever it parse a style sheet. Naturally, this approach is really expensive because it consumes more memory than a stream-based approach. As in C++, memory consumption in a DOM implementation is dependent on the size of the file, usually O(n).

That's why browsers don't implement the :has selector. Performance is a key aspect when dealing with CSS implementations and browser implementors cannot overlook this issue.

Leave a Reply

Note: Only a member of this blog may post a comment.