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">
<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"></script>
<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"});
});
});