I have HTML looks like:
<div class="group_box">
<div>
<div>
... <!-- I don't know haw many div's here -- >
<a class="mark_as_read" ...>
</div>
</div>
<div>
....
<div class="group_box">
<div>
<div>
... <!-- I don't know haw many div's here -- >
<a class="mark_as_read" ...>
</div>
</div>
<div>
I want to hide parent “group_box” when user click on “mark_as_read”.
Something like this:
<script type="text/javascript">
$().ready(function() {
$('.mark_as_read_link').bind('click', function() {
alert($(self));
$(self).parent('.group_box').hide();
return false;
});
});
</script>
But it doesn’t work. I have not idea what is $(this) in this case….
Instead of
.parent()you can use the.closest()method, which will traverse up the DOM until it finds an element that match the selector.In the example I use
.on()instead of.bind(). As of jQuery 1.7,.bind()has been deprecated in favor of.on()for attaching event listeners.Update:
As Joonas points out in his comment, it would be possible to use the
.parents()method, instead of.closest()as suggested above. The difference is that.parents()will keep traversing up the DOM, even if it encounter an element that matches the selector, while.closest()will stop traversing as soon as it finds a match. In this case I believe.closest()is more suited for the purpose, but if you consider using.parents()instead, here are the differences, stated in the documentation:.closest()
.parents()