jQuery has an awesome feature known as the context argument. It’s pretty lightly documented, but it’s extremely useful. Basically, it let’s you do selectors within a specific context. Let’s look at an example.
<div id="myParentId"> <div class="childOne">This is the first Child</div> <div class="childTwo">This is the Second Child</div> <div class="childThree">This is the Thid Child</div> </div>
The above is just a simple XHTML scenario.
// basic selector at the top level and cache in a variable var pid = jQuery('#myParentId'); // select the first child in the context of the myParentId jQuery('.childOne', pid).bind('click', function(event) { /* do stuff on click to the first Child */ }); // select the second child in context of myParentId jQuery('.childTwo', pid).bind('mouseover', function( event ){ /* do stuff on mouse over for the child*/ });
This is an overly simplistic demonstration of context, but as you can see, it’s essentially like the .find() method. Of course the above could easily be accomplished using many different methods including ‘:first‘ or ‘.eq(index)‘. However, if you are caching your jQuery objects as Dave Artz suggests in his jQuery performance rules, the context argument is super useful.