I’m wondering if there’s any advantage to using the context parameter when making selections with jQuery versus using a normal CSS scoped selector.
Assuming I have this html:
<div class="contacts">
<h1>All contacts</h1>
<div class="contact new">
<p class="name">Jim Jones</p>
<p class="phone">(555) 555-1212</p>
</div>
<div class="contact new">
<p class="name">Bob Smith</p>
<p class="phone">(555) 555-1213</p>
</div>
<div class="contact new">
<p class="name">Dave Baker</p>
<p class="phone">(555) 555-1214</p>
</div>
<div class="contact">
<p class="name">Pete Harrison</p>
<p class="phone">(555) 555-1215</p>
</div>
<div class="contact">
<p class="name">George Donald</p>
<p class="phone">(555) 555-1216</p>
</div>
<div class="contact">
<p class="name">Chris Root</p>
<p class="phone">(555) 555-1217</p>
</div>
</div>
If I want to grab all new contacts (marked by ‘new’ class) from the contacts div, which method is faster, scales better, etc..?
$('.contacts .new');
Or
$('.new', '.contacts');
Update
There’s a lot of great info strewn throughout the answers and comments. To summarize the major points, in most browsers a single selector scales better when there are multiple .contacts divs. The two selector context method is faster, in most browsers, with only a single .contacts div present.
Something useful to take away from that is we can use one method when selecting inside an element with an id.
$('p:first', '#chapter2'); // get the first paragraph from chapter 2
And use the single selector method for instances where we’re selecting from a potentially large group of elements.
$('.chapter p:first-child'); // get the first paragraph from all chapters
Against all (my) odds, seems number 2 is the fastest.
Check it here