Closest

Find the nearest ancestor that matches a selector.

Syntax$(selector).closest("ancestorSelector");

.closest(selector) starts at the current element and walks up the tree, returning the first ancestor that matches — including the element itself.

It is the go-to method inside delegated handlers to find the row or card that was clicked.

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A delegated delete button calls .closest('tr') to remove the entire table row it belongs to, not just the cell.
  • A modal close button uses .closest('.modal') to hide the dialog without knowing how deeply nested the button is.
  • A tooltip script calls .closest('[data-tooltip]') from a hover target to read the tooltip text from the ancestor's attribute.

More examples

Remove the nearest row with closest()

.closest("tr") walks up from the button until it finds the nearest <tr> ancestor and removes that row.

Example · html
<table>
  <tr><td>Alice</td><td><button class="del">Delete</button></td></tr>
  <tr><td>Bob</td><td><button class="del">Delete</button></td></tr>
</table>
<script>
$(function () {
  $("table").on("click", ".del", function () {
    $(this).closest("tr").remove();
  });
});
</script>

Close a modal from any nested button

.closest(".modal") finds the enclosing modal regardless of nesting depth, keeping the close logic generic.

Example · html
<div class="modal" style="padding:20px;background:#eee;display:inline-block;">
  <div class="modal-body">
    <p>Modal content</p>
    <div class="footer">
      <button class="close-modal">Close</button>
    </div>
  </div>
</div>
<script>
$(function () {
  $(".close-modal").click(function () {
    $(this).closest(".modal").fadeOut(300);
  });
});
</script>

Read tooltip text from ancestor attribute

.closest("[data-tooltip]") climbs the tree to find the nearest element carrying the tooltip data attribute.

Example · html
<div data-tooltip="Save your changes" class="tooltip-wrapper">
  <button class="icon-btn">&#128190;</button>
</div>
<p id="tip-text"></p>
<script>
$(function () {
  $(".icon-btn").hover(
    function () {
      var text = $(this).closest("[data-tooltip]").data("tooltip");
      $("#tip-text").text(text);
    },
    function () { $("#tip-text").text(""); }
  );
});
</script>

Discussion

  • Be the first to comment on this lesson.