tags:

views:

28

answers:

1

I have a set of nested DIV's and I need to find each outer box from the inner box. According to jQuery API, the closest() method gets the first ancestor element that matches the selector. So I've tried this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css"><!--
div{
    margin: 1em;
    padding: em;
    border: 1px solid black;
}
--></style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt;
<script type="text/javascript"><!--
jQuery(function($){
    $(".direccion-html").closest("div").css({borderColor: "red"});
});
//--></script>
</head>
<body>

<div>
    <div class="direccion-html">Foo</div>
</div>
 <div>
    <div class="direccion-html">Bar</div>
</div>

</body>
</html>

However, my closest() selector is fetching the element itself, not any of its ancestors. What am I doing wrong? It must be an obvious error but I can't get it...

Update:

I've composed this from Nick's answer:

jQuery(function($){
    $(".direccion-html").each(function(){
        $(this).parents("div:first").css({borderColor: "red"});
    });
});
+2  A: 

.closest() starts with the current element, if it's matches then that's the closest. If you want the nearest that's not the element, use .parents() with the same selector and :first, like this:

jQuery(function($){
    $(".direccion-html").parents("div:first").css({borderColor: "red"});
});

You can test it out here. Or, an alternatively route that works for many elements:

jQuery(function($){
    $(".direccion-html").parent().closest("div").css({borderColor: "red"});
});

Test that version here.

Nick Craver
Thank you, that was it. I was missing the important subtlety that it can actually match the element itself and not only its ancestors.
Álvaro G. Vicario