Why does this work:
$('.button_30').click(function(){
$(this).closest('.portlet').find('.portlet_content').text("foo");
});
any why does this not work:
$('.button_30').click(function(){
$(this).parent('.portlet').find('.portlet_content').text("foo");
});
where the html looks something like this:
<div class="portlet portlet_30">
<div class="portlet_header portlet_header_30">
header content here
</div>
<div class="portlet_sub_header portlet_sub_header_30">
<input type="text" class="textbox_30" />
</div>
<div class="portlet_content portlet_content_30">
results go here
</div>
<div class="portlet_footer portlet_footer_30">
<input type="button" class="button_30" />
</div>
</div>
<div class="portlet portlet_30">
<div class="portlet_header portlet_header_30">
header content here
</div>
<div class="portlet_sub_header portlet_sub_header_30">
<input type="text" class="textbox_30 />
</div>
<div class="portlet_content portlet_content_30">
results go here
</div>
<div class="portlet_footer portlet_footer_30">
<input type="button" class="button_30" />
</div>
</div>
Because
parent()will return the parent (immediate ancestor) only if it matches the selector specified.However,
closest()will search all ancestors and return the first one that matches the selector.As the parent of
button_30is adiv, whose parent is thedivwith the class ofportlet, theparent()function is not matching it and returning an empty set, where-asclosest()is matching it.To complete the set of similar methods here you have
parents(), which is likeclosest()but doesnt stop at the first matched element; it returns all ancestors which match the selector.