Avoid bare class selectors in jQuery

categories: 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:

Comment