Thoughts on software and life.

Monday March 20


I've noticed that there is some demand in the Ajax world to be able to search an HTML document and return a list of elements that match a CSS selector. Such a feature exists in some popular libraries like JQuery, Behaviour and Prototype, and there was a discussion of the issue recently on the WHAT-WG mailing list.

I've looked at each of these implementations and noticed them doing a lot of manual labor to search the DOM in JavaScript. This can be really really slow, and it doesn't have to be. Most modern browsers implement XPath search natively, which is fast. Since CSS is essentially a subset of XPath, why not just write a script to compile CSS to XPath?

That's exactly what I did recently when I needed to add CSS searching to FireBug. I thought I'd share my code for anybody out there who would like to try it. Note that this uses the Firefox XPath API, but translating to IE's non-standard API should be easy. I'd do it myself but I'm living in a Mac-only world at the moment.

Check out the JavaScript here: getElementsBySelector.js

Update: After doing a little research I discovered I was mistaken to think that IE allowed you to evaluate XPath. Turns out that the 'selectNodes' function doesn't work on HTML documents. Crap. Ok so my solution above really does only work in Firefox.

Posting your comment. Please Wait...