Select Closest Ancestor Matching selector .closest(selector)

.closest(selector)

e.g. $("span").closest("p")

.closest(selector) for each element in the matched set, selects closest ancestor "parenet or grand-parent..." or the element itself if matching selector.

Example 1: $("span").closest("p") will first find all <span> then select closest <p> ancestor .
<div>
  <p>
    <span>A</span>
  </p>
</div>
Example 2: $("span").closest("span") will find the closest <span> to <span> which is itself.
<div>
  <p>
    <span>A</span>
  </p>
</div>
jQuery traversing tree .closest(selector)