Monday, May 31, 2010

jQuery String Contexts

The jQuery.each() iteration function is a powerful Javascript iteration utility. You supply a callback function that is executed for each element in the provided set. Additionally, the this object in the callback function is the current element. This can cause some subtle bugs in your code if your doing string comparisons.

Since this is an object and your callback wants to do a comparison as though this were a string, it will not always evaluate to true. Even when it should be. I found this rather annoying so I tried to make sure I was in fact comparing two strings. Sure enough, this.toString() fixed my problem. So, try using this if your strings aren't evaluating as expected inside jQuery.each() callbacks.