henry henry - 7 months ago 31
Javascript Question

Selecting an element with the closest common ancestor

I need to find a way to select a DOM element that shares the closest common ancestor with a given element.

Here's what I mean:

<div class="grandparent">
<span class="match not-this-one">
<div class="parent">
<span class="match this-one">
<div class="container">
<span class="me">
</div>
</div>


I want something that does this:

$('.me').closestCousin('match'); selects <span class="match this-one">


closest() and parent() select ancestors, but don't look for cousin elements.

Answer

You can use .closest() with selector :not(.me) to exclude current element from being matched by .closest(); siblings() with selector .match

$(".me").closest(":not(.me)").siblings(".match").addClass("matched")
.matched {
  color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="grandparent">
   <span class="match not-this-one">not-this-one</span>
   <div class="parent">
      <span class="match this-one">match this-one</span>
      <div class="container">
         <span class="me">me</span>
      </div>
</div>