WebKit gets Native getElementsByClassName

getElementsByClassName is one of the more common functions requested by JavaScript programmers (and added by JavaScript libraries); it works along the same lines as getElementsByTagName and getElementById in looking up elements of a web page by their properties. In fact, it’s so common that in the new in-progress HTML5 specification it’s been added to the official DOM API. Last week WebKit joined upcoming versions of Firefox and Opera in supporting this new feature.

The advantages of a native implementation are clear:

  • No additional JavaScript library files required
  • Clearly specified and consistent behavior
  • Blindingly fast

How fast? Let’s have a look at WebKit’s shiny new implementation. For testing purposes I wrote a simple benchmark allowing comparison between three different methods for getting elements by their class names. The first is the new native getElementsByClassName, and the last two are both from prototype.js; one uses XPath, and the other is a straight JavaScript/DOM implementation.

Graph of getElementsByClassName benchmark results

The results speak for themselves. Web applications that do a lot of class lookups should see noticeable speed improvements when run with any of the native implementations, and existing JavaScript libraries can fill in for older or less advanced browsers. John Resig has run a different benchmark of the same functionality in Firefox 3 and observed a similar native vs. JavaScript/DOM speedup ratio.

Testing Methodology:
Tests were run three times, then averaged. The page was reloaded between each run. The browser used was Safari 3 with WebKit r28911. The hardware was a 2GHz Apple MacBook with 3GB of RAM running Mac OS X 10.5.1. The XPath and JS/DOM functions are from Prototype 1.5.1.