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

Posted Jun 8 2011

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.


Mathias Bynens Posted: Jun 09, 2011 @ 7:05pm

You found it here, didn’t you? :) The snippet was written by Balázs Galambosi.

darcyclarke Posted: Jun 10, 2011 @ 3:30am

Yep, that’s were I found it! Thanks for the link Mathias :) I’ve updated the post now to give credit where credits due

Derek Posted: Dec 08, 2011 @ 12:07am

Won’t :eq() accomplish the same thing?

Leave a Reply: