2

i am trying to remove a div on click on a link . the problem is there are multiple structure of same div and link and i tried making a function but it removes all div's

$(document).on("click", ".fd-bxx-cls", function(e) {
  e.preventdefault;
  $(this).parents('.fd-box2').fadeOut(300);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fd-box2">
  <div class="fd-box3">
    <a href="#" class="fd-bxx-cls"></a>
    <a class="fd-avtar-s" href="#"><img src="images/avatr_s.png" /></a>
    <div class="fd-nme-info">
      <span class="fd-mn-ttl">Robert Porter</span>
      <span class="fd-mncn-ttl">Pheonix, AZ</span>
    </div>
    <a href="#" class="ep-btns fd-msg-btn"></a>
  </div>
</div>
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39
Param Veer
  • 776
  • 4
  • 13
  • 27

2 Answers2

8

Fading out the grandparent should work.

$(this).parent().parent().fadeOut(300);

Another possibility is using .closest().

$(this).closest(".fd-box2").fadeOut(300);
Alexander
  • 23,432
  • 11
  • 63
  • 73
  • 3
    And this is inherently tied to the DOM structure. Use [`closest()`](http://api.jQuery.com/closest/) with an appropriate selector, and save yourself the need to learn exactly how many levels of nesting exists between the two objects/nodes. – David Thomas Oct 21 '12 at 10:27
  • @DavidThomas, you're right, I edited the answer to reflect your comment – Alexander Oct 21 '12 at 10:31
  • @Alexander i tried `closest` before too it didnt worked but ur parent and parent worked like a charm . Thanks you so much lot for helping – Param Veer Oct 21 '12 at 10:34
  • i just found that it only works for 2nd set of same structure and so on , but not for first – Param Veer Oct 21 '12 at 10:38
  • 1
    @ParamVeer, it works [here](http://jsfiddle.net/BZ6nJ/). You may want to update your code then, it may not reflect the reality – Alexander Oct 21 '12 at 10:41
  • @Param: could you show your `closest()`-based attempt(s)? We may be able to offer advice (because it *should* work...). – David Thomas Oct 21 '12 at 10:57
1

You should use closest() method instead of parents(). See the difference in documentation.

Also if you want to REMOVE an element (and not just hide it) use remove() method.

Slava Fomin II
  • 26,865
  • 29
  • 124
  • 202