Darcy ClarkeDevelopment / Design / UX

Toggle Main Navigation

Jun 8, 2011

Add support for nth-of-type(), and more, in jQuery

Posted in "development"


By default, jQuery doesn't support the nth-of-type() CSS selector out of the box (you can read more about why in the post by John Resig titled Selectors that People Actually Use). This was definitely an issue for me as I began to write more and more verbose HTML templates with less helper classes that normally handled that kind spacial logic. That said, I found a nice little snippet of code on StackOverflow (written by @galambalazs and documented by Mathias Bynens) one day that simply creates support for nth-of-type() within jQuery selections:

$.expr[':']['nth-of-type'] = function(elem, i, match) {
    var parts = match[3].split("+");
    return (i + 1 - (parts[1] || 0)) % parseInt(parts[0], 10) === 0;
};

This is a pretty straightforward snippet but if you want, Keith Clark (the rad dude behind Selectivizr) has put together a nice little plugin that adds all the xxx-of-type() selectors to jQuery. Check out the project on github here.