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 */ });- 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');
