Helvensteijn.com

Life is like photography
we use the negatives to develop

Jump to menu

µ: An über small “selector engine”

I’m probably not the first one to come up with this, but if you’re writing some sort of web app that’s sure to run in modern browsers (iOS and Android devices for instance) then the following 75 bytes are all you need as a selector engine:

function $(s,c){return [].slice.call((c||document).querySelectorAll(s),0);}

If you need to test an element against a selector (handy for event delegation):

$.matches = function(e,s){return $(s).indexOf(e)>-1;};

There’s also a webkitMatchesSelector() method on elements which could be used instead (and will be faster) but It was first introduced in September 2009, so it’s not as ubiquitously supported as [].indexOf() is in modern browsers. Plus it has a vendor prefix, which means feature testing isn’t as straightforward as simply testing for one function. Gecko has a mozMatchesSelector() equivalent since October 2009 and Opera will no doubt soonish have an implementation named either oMatchesSelector() or just matchesSelector().