Closest – New Traversal Method in jQuery 1.3

by Bill Beckelman 19. July 2009 09:32

Have you noticed the new traversal method in jQuery 1.3+ named “closest?” I hadn’t until a few days ago when it came in pretty handy when I was working on some client side error handling using the jquery.validate plugin. So what does closest do? From the jQuery docs:

“Get a set of elements containing the closest parent element that matches the specified selector, the starting element included. Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.”

Here  is a quick contrived example:

<div class=”wrapper>
    <div>
         <label for="Street">Street:</label>    
         <input id="Street" type="text" class="error" />
    </div>
</div>

If I wanted to find the closest div with a class of “wrapper” in relation to the input in an error state signified by having the class “error” and give is a different background or something I could now use the following:

$(function() {
   $(".error").closest(".wrapper").addClass("error-background");
});
 

Of course in this contrived example it would be more efficient to walk up the tree ourselves since we know the exact structure, but imagine a situation where you have dozens of form fields with a varying structure and you need to find the wrapper of each field that might be in error.

 

   kick it on DotNetKicks.com

Tags:

jQuery

Comments

Comments are closed

Powered by BlogEngine.NET 1.4.5.7
Theme by Mads Kristensen


About Me

I live and work in Salt Lake City, Utah. My background is in aviation. I have a degree in Aeronautical Science from Embry-Riddle Aeronautical University in Prescott, AZ. I have worked as a commercial airline pilot and most recently as a technical advisor for a charter airline.