Chapter 15. CSS selector engines

 

This chapter covers

  • The current status of browser selector support
  • Strategies for selector engine construction
  • Using the W3C API
  • Some info on XPath
  • Building a DOM selector engine

The good news is that we, as web development professionals, are well into the age in which the W3C Selectors API exists in all modern browsers. This API (which has two levels: Level 1 and Level 2) provides us with the querySelectorAll() and querySelector() methods, along with other goodies that we can use in our applications to write very fast DOM traversals in relatively cross-browser ways.

Note

Want more info on this API? See the W3C pages for Level 1 (www.w3.org/TR/selectors-api/) and Level 2 (www.w3.org/TR/selectors-api2/).

You might ask, as the W3C Selectors API has been implemented in virtually all modern browsers, why do we need to spend time discussing how a pure JavaScript CSS selector engine is implemented?

Although the addition of the standard API is a good thing, the implementation of the W3C Selectors API in most browsers (at least in their mid-2012 state) is rather a shoehorning of existing internal CSS selector engines into the standardized JavaScript/DOM realm. To make this happen, a number of niceties that one would typically associate with a good API were set aside. For example, the methods don’t make use of already-constructed DOM caches, they don’t provide good error reporting, and they’re unable to handle any form of extensibility.

15.1. The W3C Selectors API

15.2. Using XPath to find elements

15.3. The pure-DOM implementation

15.4. Summary