There are two easy ways to select odd rows in a table with jQuery, using the :odd filter, or the :nth-child(odd) selector;
$('table tr').filter(':odd')
$('table tr:nth-child(odd)')
What are the benefits and drawbacks of each method? Mainly wondering in terms of execution speed and browser support.
The first method with
.filter(':odd')is most probably slower, because it uses an additional method call and it uses a non-standard selector. jQuery has to handle everything in this case.The second method will potentially be faster in modern browsers that implement the Selectors API and support the
:nth-child()pseudo-class, as your given selector is valid CSS, so the selector will be evaluated by a modern browser’s selector engine rather than jQuery. In other browsers, though, I have no idea, but I’d still bet on the second method being fractionally more efficient because there is at least one less method call.Either way, there is no real (practical) benefit or drawback to either method. In fact, I’m only answering theoretically — I don’t really have any benchmarks to back anything up. There is also no need to worry about browser compatibility as jQuery polyfills the
:nth-child()selector for older browsers anyway.