To $('#foo p') or to $('p', $('#foo'))

24 February 2009   2 comments   Javascript

Powered by Fusion×

For the performance interested jQuery users please check out this thread

For the impatient, read Stephens reply He benchmarked what I asked and concluded that $("p", $("#foo")) is much faster in jQuery 1.3.2. I've been coding this style in jQuery for all recent projects so I'm happy with this outcome.


John Resig himself joined in on the discussion and had this to say:

"You should always use $("#foo").find("p") in favor of $("p", $("#foo")) - the second one ends up executing $(...) 3 times total - only to arrive at the same result as doing $("#foo").find("p")."


Not only did John join in on the discussion but it also made him work on jQuery 1.3.3 (not yet released at the time of writing) so that it doesn't matter which format you use you get the same performance. See the benchmark here


Why not simply: $("#foo").find("p");

The syntax is more clear and readable, and jQuery isn't called twice.

Performance wise, they are practically equivalent.
Peter Bengtsson
See my update in the blog post.

Your email will never ever be published

Related posts

Propeller Island City Lodge Orange Room 23 February 2009
Sandisk SSD v/s HDD 04 March 2009
Related by keywords:
Fastest way to uniqify a list in Python 14 August 2006
Difference between $.data('foo') and $.attr('data-foo') in jQuery 10 June 2012
Optimization of getting random rows out of a PostgreSQL in Django 23 February 2011
Local Django development with Nginx 11 October 2010
Why I gave up on JQuery UI's autocomplete 20 October 2010
Lesson learnt with creating DOM element with jQuery 04 April 2008
Ruby and Python benchmarked 25 September 2005
jQuery and Highslide JS 08 January 2008
PostgreSQL, MySQL or SQLite 04 April 2004
Date formatting in python or in PostgreSQL 20 July 2004
In jQuery, using the :visible selector can be dangerous 14 September 2010
Why Django and Grok matters 02 February 2008