Avoid Bare Class Selectors In jQuery
It just happened again: I was looking at someone else's jQuery and I came across something like this:
$('.button').click(function() { /* do something */ });This is a classic case of "just because you can, doesn't mean you should." This little bit of jQuery will, indeed, find every element on a page with a class of "button", but that's exactly the problem: it has to look at every element on the page to figure out which ones match the selector. It seems short and sweet, like so much of jQuery is, but on a page with a lot of elements, this selector can actually take a non-trivial amount of time to run.
There are a few ways to avoid this:
- If the element you're after has an ID attribute, use it. That's the single-fastest way to find an element. However, don't gratuitously add ID attributes to elements; the other methods below are perfectly good.
- Specify the type of element you're after. For example,
$('input.button'). This will tell jQuery that it's only looking for inputs, so it can disregard anything on the page that isn't an input. If you're looking for multiple element types, tell jQuery that:$('input.button, a.button') - Give jQuery some information about where to look for the element. For example:
$('#myForm .button') - Use an element you've already found to tell jQuery where to find the element:
var $ul = $('#myUnorderedList')
var $li = $ul.find('.selected');
- Login or register to post comments
- 2809 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)










Comments
Stephen Jennings replied on Thu, 2008/12/11 - 8:52am
great advice. I had already started using the element.class/element#id approach.
Here is a question I have about jQuery selctors, which is better?
To select the wrapper element then use the 'find' or use the 'children' methods for navigation? I just ask cause lots of people do it different ways.
adrian.salceanu replied on Sat, 2008/12/20 - 2:43pm
As usual, the best ideas are the most obvious ones - thanks for the tip.
But, you should also take this into account: from a semantic / logic perspective, you should use CSS classes for styling repeating elements. If the style is not repetitive, than a CSS class is not needed in the first place - you can use an id or more complex CSS selectors. So, if you do things right from the start, you will use a CSS class only for multiple elements, and in consequence you will correctly use the CSS class jQuery selector, to affect all those elements.