It’s all about context
One big selling point of jQuery – so everyone says – is the ability to nest/chain selectors, so that using oen string you can, in theory, pick out any element in the DOM. But this has eluded me somewhat until today; until I realised the usefulness of setting a context for jQuery selectors.
I noticed a few days ago that my new crossSelect plugin was a bit inefficient, in that it queried the DOM far too often. It used to have something like the following code:
$(this).parent().parent().find('.target1').children('li')...
$(this).parent().parent().find('.target2').children('li')...
But the next iteration was going to have something like this instead – far sleeker.
var context = $(this).parent().parent()
$(context).find('.target1').children('li')...
$(context).find('.target2').children('li')...
But it bugged me that I couldn’t pick out the <li>’s with a string selector. This is because context is an object, not a string, and therefore can’t be a part of a selector string. But then I discovered setting the context on selectors (easy to miss as it’s not linked to from the selectors bit of the documentation site). So that led to the following:
$(context).find('.target2').children('li');
is equivalent to
$('.target2', context).children('li');
which can be rewritten
$('.target2 > li', context);
Far more elegant, I think you’ll agree. So it’s jQuery context setting all the way for me. From now on I will only use find when I need to find a child element on the same line that I’ve already done something to the parent; it really has no place at the begining of a line of jQuery code.
No related posts.
Tags: chaining, context, crossselect, jquery, selectors