<p>In my javascript experience, I found that is a very common task "searching the nearest ancestor of an element with some condition (tag name, class,...)". 
Can the parents() method of jquery do the job? The order of returned elements of parents() is predictable? Is top-to-bottom or bottom-to-top? 
For the moment I use this utility function:</p>

<pre><code>function ancestor(elem, selector) {
  var $elem = $( elem ).parent();
  while( $elem.size() &gt; 0 ) {
    if( $elem.is( selector ) ) 
    return $elem;
    else
       $elem = $elem.parent();
  }
  return null;
}
</code></pre>

<p>Can someone tell me if there is a clever way to do the job?</p>

Edit
: Since jQuery 1.3, this has been built in as the
```
closest()
```
function. eg:
```
$('#foo').closest('.bar');
```
yep - parents() traverses up the tree.
```
```
<div id="a">
    <div id="b">
        <p id="c">
            <a id="d"></a>
        </p>
    </div>
</div>
```
```
```
$('#d').parents("div:first");
```
will select div b.