1

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I wasn't sure if jQuery would handle the selector if it wasn't supported by the browser. Do you have a link to source for that, just out of interest? :)
@Joe: It's all in the front page :)
1

Browser support shouldn't be an issue, as jQuery works well in all modern-ish browsers: http://docs.jquery.com/Browser_Compatibility

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.