Use closest instead to prevent iterating through all ancestors: http://api.jquery.com/closest/
Also http://api.jquery.com/first-selector/
"To achieve the best performance when using :first to select elements, first select the elements using a pure CSS selector, then use .filter(":first")."