Why closest() find first itself element before travesing tree

I looking for why closest() find first itself element before traversing tree.

For example: I would like fadeOut the parent div element when i click on children element, but the children element is too a div and so is the children who fadeOut

$(document).on("click", ".close", function() {
  $(this).closest("div").fadeOut();
});
.feed {
  width: 200px;
  height: 200px;
  background: red;
  position: relative;
}
.close {
  position: absolute;
  top: 0;
  right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="feed">
  <div class="close">
  X
  </div>
</div>

Why is itself element who fadeOut and no the parent div element?

I know parent() get the parent element, but closest() is supposed traversing elements tree.

Have you a concrete cases, where get itself is useful?


solution

It’s because the .closest() method traverses the DOM beginning with the current element. You may want the .parents() method instead since it will begin with the parent element.

$(this).parents("div").fadeOut();

It’s worth noting that the .parents() method returns zero or more elements whereas .closest() will return zero or one element. Therefore you might want to chain .first() after the .parents() method in order to get the first match:

$(this).parents("div").first().fadeOut();

$(document).on("click", ".close", function() {
  $(this).parents("div").first().fadeOut();
});
.feed {
  width: 200px;
  height: 200px;
  background: red;
  position: relative;
}
.close {
  position: absolute;
  top: 0;
  right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="feed">
  <div class="close">
  X
  </div>
</div>

Alternatively, you could also just exclude the parent by selecting the parent element and then using .closest() like:

$(this).parent().closest("div").fadeOut();

However, it would be much better just to select the closest .feed element rather than any div:

$(this).closest(".feed").fadeOut();

$(document).on("click", ".close", function() {
  $(this).closest(".feed").fadeOut();
});
.feed {
  width: 200px;
  height: 200px;
  background: red;
  position: relative;
}
.close {
  position: absolute;
  top: 0;
  right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="feed">
  <div class="close">
  X
  </div>
</div>