user99999 user99999 - 3 months ago 11
HTML Question

Getting element before parent

I have the following dom tree:

<tr class="tomatch" id="123"></tr>
<tr>
<td>
<div>
<span class="matching"></span>
</div>
</td>
</tr>


I have a
$(this)
object set to
.matching
element, and I have to get
.tomatch
element from it. How can I do this?

parent()
won't work, I tried using
.prev()
or
prevUntil('.tomatch')
, but it doesn't work either. Same thing with
.closest('.tomatch')
and
.parents('.tomatch')
.

How can I do this? I have to match the first element before tr parent, because this structure is repeatable.

Answer

.closest and .parents are for finding elements that are ancestors of the specified element, but the element you want is a sibling of an ancestor. So you need to do it in two steps -- first go up to the ancestor, then go to the previous element from there.

$(".matching").click(function() {
  console.log($(this).closest("tr").prev().attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr class="tomatch" id="123"></tr>
  <tr>
    <td>
      <div>
        <span class="matching">Click here</span>
      </div>
    </td>
  </tr>
</table>