JOEHEWITT.COM

Quasi-daily thoughts. No cute taglines.

Monday March 20

Spoiled

After a long hiatus, I'm diving head first back into DHTML/Ajax development. Am I insane?

This is going to hurt. I've been seriously spoiled for 6 years, working primarily with the pristine DOM of Mozilla/Firefox and the even more lovely Boxely. I had access to the source of both and could implement new features at the C++ level whenever I needed them. Now I am back to the world of unseemly JavaScript hackery.

6 years ago I had every quirk of every browser etched on my brain. Mozilla was still just a dream, IE5 was my love, and Netscape 4 was my bitch. Now today Mozilla is a dream come true, Netscape is dead, Safari and Opera are in the mix, and IE6 is about to become my bitch.

My previous post is evidence of how effectively I have purged my brain of all the miserable incompatibilities of the cross-browser world. I just assumed that IE supported XPath, since I had read about the 'selectNodes' function. Silly me, that only works on XML documents! Come back to me in a few months and I'm sure I'll be able to recite every insipid workaround ever dreamed up for Microsoft's sad little orphan. My poor little brain.

getElementsBySelector

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.

at
Posting your comment. Please Wait...